When I compile the code below
#include<stdio.h>
int main()
{
int a;
int a = 10;
printf("a is %d \n",a);
return 0;
}
I get an error:
test3.c: In function ‘main’:
test3.c:6:5: error: redeclaration of ‘a’ with no linkage
test3.c:5:5: note: previous declaration of ‘a’ was here
But if I make the variable global then it works fine.
#include<stdio.h>
int a;
int a = 10;
int main()
{
printf("a is %d \n",a);
return 0;
}
Why is declaring the same global variable twice not an error, but doing that for a local variable is an error?
Comparison Chart Between Global Variable and Local VariableGlobal variables are declared outside all the function blocks. Local Variables are declared within a function block. The scope remains throughout the program. The scope is limited and remains within the function only in which they are declared.
A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.
Redeclaration: In C, you cannot redeclare a variable within the same scope. However, you can overwrite a global variable's declaration locally. This is generally a bad practice, unless you have a global variable that behaves(should take some other value) differently in certain functions.
The other reason I could think of is that un-initialized global variables are stored in the BSS (Block Structured Segment) where are the global variables that are initialized are stored in Data Segment.
I am guessing that there is some kind of a name space resolution and when there is a conflict the variable in the Data segment overrides the one in the Block Structured Segment.
if you were to declare
int a =5 int a = 10
in the global scope (both in the data segment) there would be conflict as expected.
In C, the statement int a;
when made at file scope, is a declaration and a tentative definition. You can have as many tentative definitions as you want, as long as they all match each other.
If a definition (with an initializer) appears before the end of the translation unit, the variable will be initialized to that value. Having multiple initialization values is a compiler error.
If the end of the translation unit is reached, and no non-tentative definition was found, the variable will be zero initialized.
The above does not apply for local variables. Here a declaration also serves as a definition, and having more than one leads to an error.
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