Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of global variables using a non constant initializer

#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?

like image 792
Vignesh_dino Avatar asked Dec 09 '12 06:12

Vignesh_dino


People also ask

Do global variables have to be constant?

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.

How do you define a global variable?

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.

What is a global constant variable?

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.

What are global variables initialized to?

In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value.


1 Answers

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.

like image 160
Alok Save Avatar answered Sep 20 '22 00:09

Alok Save