user123 user123 - 2 months ago 7
C Question

why cant we assign a value to global variables using an expression in C ?

In the below code snippet , I am trying to assign a value to a global variable using an expression but it gives the error "initializer element is not constant" ,I am unable to get the logic behind this ,please clarify this .

#include<stdio.h>
int a=8;
int b=a+9;
int main()
{
printf("%d",b);
return 0;
}

Answer

You can assign a global variable using an expression. But only inside a function. As said by the compiler/linker, outside a function you can initialize variables only to constant. This is because, outside a function, no code can be executed and the variables are initialized to constant value by the compiler/linker at build time. Note that if you don't init the variable (outside a function), the default initialization is to 0. To make it work you should write

#include<stdio.h>
int a=8;
int b;
int main()
{
   b=a+9;
   printf("%d",b);
   return 0;
}