Static Variables are Initialized at Compile Time
Consider the Two programs given below.
//Program 1
#include<stdio.h>
int aaa=10;
int main()
{
static int bbb=aaa;
printf("Value is %d\n",bbb);
return 0;
}
Download
//Program 2
#include<stdio.h>
const int aaa=10;
int main()
{
static int bbb=aaa;
printf("Value is %d\n",bbb);
return 0;
}
Download
Both the programs will give you the following error message on Code::Blocks 10.05, "Initializer element is not constant". Reason? Static variables are initialized at compile time. So either it should be initialized with a constant value or leave the initialization to the compiler, which will initialize the static variable to zero.
The program given below corrects the error.
#include<stdio.h>
#define aaa 10
int main()
{
static int bbb=aaa;
printf("Value is %d\n",bbb);
return 0;
}
Download
The program below declares bbb as an automatic variable and there are no errors. Remember the default storage class is automatic (auto).
#include<stdio.h>
int aaa=10;
int main()
{
int bbb=aaa;
printf("Value is %d\n",bbb);
return 0;
}
Download
No comments:
Post a Comment