I know I will get many down grade regarding this question, but I still write following test code:
int *gPtr;
//I know I can NOT write below code line, but I need know WHY
gPtr = NULL;//or some other value which I want to init it
//int *gPtr = NULL; //this line should be OK
int main (void)
{
int *ptr;
ptr = NULL;
return 0;
}
The global *gPtr
during compile will output error:
ptr.c:4:1: warning: data definition has no type or storage class [enabled by default]
ptr.c:4:1: error: conflicting types for ‘gPtr’
ptr.c:3:6: note: previous declaration of ‘gPtr’ was here
ptr.c:4:8: warning: initialization makes integer from pointer without a cast [enabled by default]
However, in the function, I did same code, but no compile error/warning, I would like to know:
int a = 0;
and int a; a=0;//no other code between these two sentences
please give me advise for above three questions according to the compiler view(or you think it should have other explanation in some others view like coding standard?)
You can define a global variable with an initial value:
int *gPtr = NULL;
But you cannot do an assignment outside of a function scope. The compiler (well, at least my clang compiler) actually interprets
gPtr = NULL;
in the global scope as
int gPtr = NULL;
which causes similar warnings and a conflicting types error:
warning: type specifier missing, defaults to 'int' [-Wimplicit-int] gPtr = NULL; ^~~~ error: redefinition of 'gPtr' with a different type: 'int' vs 'int *' note: previous definition is here int *gPtr;
Global variable without an explicit initial value are automatically initialized to zero, therefore in your case
int *gPtr;
would be sufficient (as @WhozCraig already commented above).