I have declared global variable again after the main function but It still affects main function. I know that C allows a global variable to be declared again when first declaration doesn’t initialize the variable(It will not work in c++). If I assign the value after the main function it still works with two warning in c but gives error in c++.
I have debugged the code but it never reaches the line int a=10;
.
#include <stdio.h>
#include <string.h>
int a;
int main()
{
printf("%d",a);
return 0;
}
/*a=10 works fine with following warnings in c.
warning: data definition has no type or storage class
warning: type defaults to 'int' in declaration of 'a' [-Wimplicit-int]|
but c++ gives the following error
error: 'a' does not name a type|
*/
int a=10;
The output is 10
.
Several things:
The first int a;
is a tentative declaration; the second int a = 10;
is a defining declaration.
a
is declared at file scope, so it will have static
storage duration - this means that storage for it will be set aside and initialized at program startup (before main
executes), even though the defining declaration occurs later in the source code.
Older versions of C allow for implicit int
declaration - if a variable or function call appears without a declaration, it is assumed to have type int
. C++ does not support implicit declarations, so you will get 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