#include <stdio.h>
int i=10;
int j=i;
int main()
{
printf("%d",j);
}
I get an error stating that initialization element is not a constant? What is the reason behind this?
Global variables aren't constant (you can change the value of a global variable, but you can only define a constant once). Constants aren't always global (you can declare a constant in a class). Also, global variables can be any type: scalar, array, or object.
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.
In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value.
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.
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