Hi I was just wondeing if it was possible to create a variable inside a function but give it a global scope.
x = 2;
I know the easy way would be to just put it in main, but this is more for my curiosity as such
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.
Originally Posted by PING
Note also that there is the possibility of having a "local data space", which is a "static local" - e.g.
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.
static int x = 7;
// change x.
No, it's not possible, nor should it be, because it would make it global, thus making it no different from a global variable.
Originally Posted by Matty_Alan
If you want functions to communicate with each other, they can pass arguments between each other, or they can return values.
T* <--- return type
T arg1 <--- Parameter (argument)
T* function_name(T arg1);