So, let's say, I have:
file1.c
int i;
static int j;
int main ()
{
for ( int k = 0; k < 10; k++ )
{
int foo = k;
}
}
file2.c
{
// the following statements are before main.
extern int i; // this is acceptable, I know since i acts as a global variable in the other file
extern int j; // Will this be valid?
extern int foo; // Will this be valid as well?
}
I therefore, have a doubt that the statements marked with a question mark, will they be valid?
Difference between static variables and global variablesStatic variables can be declared both inside and outside the main function while the global variables are always declared outside the main function.
Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.
A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.
static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files. A local variable defined in a function can also be declared as static .
No! static
globals have file scope (internal linkage), so you can't use them as they have external linkage... This does not means that you cannot have a variable of the same name with external linkage but it cannot be that one that is static
.
Correct for i
.
Incorrect for j
, at least it cannot be the one defined in file1.c
.
Incorrect for foo
, at least for the local variable used in file2.c
which does not have external linkage (no linkage at all). A local variable only exists when the block where it is declared is activated, so having access to it outside is a non-sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With