#include
int i=10;
int j=i;
int main()
{
printf(\"%d\",j);
}
I get an error stating that initialization element is not a const
You could try using:
int i=10;
int j=0;
int main()
{
j=i;//This should be the first statement in the main() and you achieve the same functionality as ur code
return 0;
}
The only true C way is to initialize it at runtime. Although in C++ your code will work fine, without any compilation errors.
The C standard clearly prohibits initialization of global objects with non-constant values. The Section 6.7.8
of the C99 standard says:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
The definition of an object with static storage duration
is in section 6.2.4:
An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
Use this:-
int i=10,j=1;
int main()
{
printf("%d",j);
}
Though it is a minor change but it will work
What is the reason behind this?
C(unlike C++) does not allow initialization of global values with non constant values.
C99 Standard: Section 6.7.8:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
The idea behind this requirement is to have all static storage duration object initialized at compile time. The compiler prepares all static data in pre-initialized form so that it requires no additional initializing code at run time. I.e. when the compiled program is loaded, all such variables begin their lives in already initialized state.
In the first standardized version of C language (C89/90) this requirement also applied to aggregate initializers, even when they were used with local variables.
void foo(void)
{
int a = 5;
struct S { int x, y; } s = { a, a }; /* ERROR: initializer not constant */
}
Apparently the reason for that restriction was that the aggregate initializers were supposed to be built in advance in the pre-initialized data segment, just like global variables.