PDA

View Full Version : Declaring global variables inside a function, in C?



crazyfuturamanoob
November 11th, 2008, 04:37 PM
This is a very dumb question but haven't still found answer.

dexter
November 11th, 2008, 04:44 PM
Declare them static, e.g.


static int i;


What exactly is your purpose?

dwhitney67
November 11th, 2008, 04:44 PM
Not a dumb question at all.

The answer is that it cannot be done. The variable will only have scope within the function.

Global variables must be declared outside of a function scope (and before you think otherwise, main() is a function too). Globals are declared within header files or within .c modules.

P.S. I should point out that when developing a project with multiple .c modules, one of them must instantiate the global variable; the other(s) must declare it as an "extern" variable. Otherwise if two or more modules each have their own instantiations of the variable, the compiler will not be happy with that.

snikrot
November 11th, 2008, 04:51 PM
Why do you wish to declare a global variable inside a function. The variable wouldn't be known to other functions.

See also http://www.cplusplus.com/doc/tutorial/variables.html

It would be easier to declare the variable outside the function and give it a value inside it. Or even better take a pointer outside the function with the value NULL and inside the function set it to the correct value.

crazyfuturamanoob
November 11th, 2008, 05:17 PM
I wanted to have an initializition function which declares some variables and makes them global, because I thought it's one keyword which makes them global.

Doesn't matter me much. Thanks.

LaRoza
November 11th, 2008, 05:28 PM
I wanted to have an initializition function which declares some variables and makes them global, because I thought it's one keyword which makes them global.

Doesn't matter me much. Thanks.

You could declare the variables as global, then use a function to give them a value.