Variable Scope

This is a discussion on Variable Scope within the C Programming forums, part of the General Programming Boards category; Hi I was just wondeing if it was possible to create a variable inside a function but give it a ...

No, you can't do that. Global variables are allocated on the heap while local variables are allocated on the stack. When your function returns, the stack space used by the function is free and can be used by the next function which will be called or occupied by other variables in your code. Global data on the other hand is not popped out in this fashion when functions return.

No, you can't do that. Global variables are allocated on the heap while local variables are allocated on the stack. When your function returns, the stack space used by the function is free and can be used by the next function which will be called or occupied by other variables in your code. Global data on the other hand is not popped out in this fashion when functions return.

Whilst you are right that local variables are on the stack, and thus disappear when the called function returns, the global variables actually get their space allocated at runtime in a region called "Data" (or some similar name, differnet OS/Compiler variants vary a bit). The heap is used for malloc in C and new in C++ to create permanent space for variables when the application is running.

Note also that there is the possibility of having a "local data space", which is a "static local" - e.g.

Code:

void function(void)
{
static int x = 7;
// change x.
}

In this case, x is not on the stack, it is a global variable, but only visible within this function. The purpose of this is to "remember" things from one call to another, for example.

Hi I was just wondeing if it was possible to create a variable inside a function but give it a global scope.

No, it's not possible, nor should it be, because it would make it global, thus making it no different from a global variable.
If you want functions to communicate with each other, they can pass arguments between each other, or they can return values.