Initializer element is not constant ошибка

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A «large» object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term «constant» refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */

The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */

you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

1. First, solve the problem of error reporting as shown in the title;

Take a look at the following code:

#include <stdio.h>  
int a = 1;  
int b = 2;  
int c = a+b;  
  
int main() {  
    printf("c is %d\n", c);  
    return 0;  
}  

Error during compilation of GCC-O test test.c: Initializer Element is not Constant

Reason: the value of the global variable C cannot be determined at compile time; it must be determined at run time. Why is that?Because this is the standard:
C language standard: Initializers of external variables and static variables must be constant expressions [1].
So the solution:

#include <stdio.h>  
int a = 1;  
int b = 2;  
int c; 
  
int main() {  
    c = a + b; 
    printf("c is %d\n", c);  
    return 0;  
}

———-
Similarly, the following code does not compile, and the error message is the same as above: [4]

char * p1 = (char *) malloc(10);  
int main(void)
{
。。。   
}

2. Do GCC and g++ compile according to the suffix name of the file?

If you change the source file name *.c to *.cc, and then compile with g++, no error will be reported. Even if you just change the file name to *.cc, the compiler will also compile with GCC, which can also compile the past. What is the reason?

————–
Principle:
GCC started out as GNU C Compiler, which is, as you know, a C Compiler. But later, as the project integrated more compilers in different languages, GCC stood for the GNU Compiler Collection, thus representing a Collection of compilers.
So instead of calling GCC when you compile your code, it’s more like a driver that calls the c compiler or the c++ compiler (g++) based on the suffix of your code. For example, if your code suffix is *.c, it will call the C compiler and linker to link to C’s library. If your code suffix is CPP, it will call the g++ compiler, and of course the library call will also use the c++ version (however, the GCC command does not automatically link to the library used by c++ programs, you must follow the parameter gcc-lstdc ++)

—————–
Here’s a piece of code:

#include <iostream>

using namespace std;

int a = 1;
int b = a;

int main()
{
cout << b << endl;

}

The Initializer Element is not constant because GCC identifies the code as C, and C specifies that initializing global variables must be a constant expression.
If $GCC test.cc, undefined reference to ‘STD ::cout’… Wait… Error: ld returned 1 exit status. Although GCC recognized c++ code at this time, it would not automatically link c++ code base, so ld link error appeared. At this point only need to manually specify and C ++ library link C: $GCC test.cc-LSTDC ++, at this point you can smoothly through the compilation link.

———————
G++ is the c++ compiler for GCC. At compile time, g++ calls GCC, so for c++ code, the two are equivalent. But since the GCC command does not automatically associate with the library used by c++ programs, it is common to use g++ for linking, so for the sake of uniformity, compile/link all use g++, giving the illusion that c++ programs can only use g++.
So you can understand it this way: you can compile with GCC /g++, and you can link with either g++ or gcc-lstdc ++. Because GCC commands do not automatically join with libraries used by C++ programs, g++ is usually used to complete the join. But at compile time, g++ automatically calls GCC, which is equivalent.
For the above code, just $g++ test.c will compile because g++ identifies *.c files as c++ files [2].

The compiler is through the program suffix name to determine the language is C or C ++. Specifically, if the suffix is.c, GCC treats it like a c program, and g++ treats it like a c++ program; CPP suffix, both are considered as c++ programs, note that although c++ is a superset of c, but the syntax requirements of the two are different [2], for c language and c++ language suffix name problem, see [7]
(3) for 1 is the C language standard, not C++, for C++, global variables and static variables do not have to follow the initialization must be constant expression such requirements, so, if the compiler to identify the above code into C++ code, then it can be successfully compiled in the past. (And the program USES the same libraries as the C language, so it’s ok not to add -LSTDC ++ parameter.

Therefore, since the suffix name of the file is changed to *.cc, I guess that whether GCC or g++, this file is identified as c++ file, so it is clear that since it is identified as c++ file, of course not to report an error.

3, compiler strong and weak symbols

In C, global variables default to 0 if they are not initialized, that is, in the global space:
int x =0; With the int x; The effect looks the same. The difference is very big, but here it is strongly recommended that you all global variables
to initialization, the main difference between them is as follows:

the compiler when compiling for both conditions can produce two kind of symbols in the symbol table of the target file, for initialization, called
symbol, an uninitialized, called weak symbols.

if the connector encounters two duplicate symbols while connecting to the target file, it will have the following processing rule:
if there are strong symbols with multiple duplicate names, it will report an error.
if there is a strong symbol and more than one weak symbol, the strong symbol shall prevail.
if there is no strong symbol, but there are more than one weak symbol with the same name, then choose any weak symbol.

————-
So here’s a piece of code:

#include<stdio.h>
int i;
i =1;
int main()
{
printf("%d\n", i);
}

GCC test. C
Can be compiled, but with warning: Data Definition has no type or Storage class
What does that mean?I =1, the definition of an I variable has no type;
So the code looks like this:

#include<stdio.h>
#include<stdlib.h>
 
int i;
j=1;
 
int main()
{
printf( "%d\n", j);
printf( "%d\n", i);
system( "pause" );
return 0;
}

gcc test.c
This code also has warning; data definition has no type or storage class
So for I =1; The compiler takes it as the definition + initialization of a variable.
and the int I before; Because I is equal to 1; So int I is weak, it doesn’t work; [3]

However, the above two pieces of code, if using g++ compiler, that is, according to the rules of c++ compiler, will be directly error:
“J does not name a type” because c++ is a mandatory language, can not be so casual!
It is worth noting that the first paragraph of the above two code also reports an error in g++ : “I does not name a type”. It is understandable that j compilation should not pass, because j is not defined at all. Int I = 1; int I = 1; Int j = 2; int c = a+b; G++ is passable. What’s the problem?See section 4 of this article.

————–
Here’s another piece of code:

#include <stdio.h>
struct stu
{
   long number;
};

struct stu  student; 
student.number = 1;  

int main(int argc, char * argv[])
{
 printf("%d\n", student.number);
}

Why is that?
The assignment statement should be placed in the function body!
Initialization can be outside the body of the function… But the assignment must be inside the body of the function…
Moreover, not only are structures assigned, but most statements (other than declarations and definitions of functions and variables) do not allow…
So understand the difference between initialization and assignment;
(This applies to C and C ++)
**** It should also be noted that in C language, struct is required when defining structural variables, while in C ++, it is not required. Stu Student = {1}; You can, but with struct you can compile it, you can run it.

4. Why is it specified that the initial values of global and static variables must be constant expressions?
Now that we’ve solved the problem, and we’ve analyzed why we did it, we can go deeper. Why do global variables and static variables have to be initialized as constant expressions?
Global (static) storage: Divided into DATA segments and BSS segments. The DATA section (global initialization section) holds initialized global and static variables; The BSS section (global uninitialized area) holds uninitialized global and static variables as well as initialized to zero global and static variables (see here). Automatic release at the end of the program. The BBS section is automatically cleared by the system before the program execution, so uninitialized global variables and static variables are already 0 before the program execution. – The program is released by the system after completion. [5]
——-
A comparison, for the statement:

int i = 3
int main()
{
    int j = i;
    ...
}

Instead of determining the value of the local variable J at compile time, the value of I is read at run time to assign to J. The compiled connected executable does not contain the value of J, only the code for the corresponding assignment statement. In contrast, since I is a global variable and is stored in static storage, its value needs to be determined at compile time. Space will be allocated in the target file to store the value of I. There will be no assignment statement to assign the value of I at run time, and there is no corresponding code.

for the statement:

int i = 3;
int j = i;

Because J is a global variable and is stored in static storage, its value also needs to be determined at compile time. I is a variable, not a constant, and the value of I cannot be determined at compile time, which means that the value of J cannot be determined at compile time, so C will report an error.
Instead, C++ simply puts j as an uninitialized global variable in the.bss area at compile time, with the default value of 0, and then adds a statement to assign j at run time, ensuring that this statement is executed before the main function begins. So the initialization of j is actually done at run time. [6]

So, we can now answer the question raised in red in section 3:
1. For int I = 1; int j = 2; int c = a+b; This sentence, in g + + through because the statement is the c at compile time as a variable declaration, because the front of the variable c has keyword int, then the compiler will be additional add a statement c = a + b, and ensure that the statement before the main function, g + + this way to make this statement to the right by compiling.
2. For int I; I = 1; G++ does not compile. The reason is that an assignment statement like I = 1, which is different from an int c = a+b, requires a value at run time; I =1 cannot be regarded as a declaration of a variable (I variable has no type in front of it),,,,,,, etc

Tip: GCC compiler plus the -v parameter, displays compile-time details, compiler version, compilation process, etc.

Read More:

In this article, we will be discussing a compiler error that a programmer often gets while coding in C++ Language: the “Initializer Element is not Constant”. To understand the error first, we need to understand the background of initializers and global variables. So, global variables are those variables that a programmer defines at the top of the code outside the functions. A variable that is declared globally will hold the value that is stored in it throughout the execution of code and will not lose it once a function is executed.

The advantage of the global declaration of variables is that they can be used in any function and any part of code. This means, we can use them and their values throughout our code. It is necessary for C++ programming that global variables should be initialized with constant expressions. If a programmer or coder forgets or is unable to do so, it will cause the error being discussed here. This error is also caused if static variables are also not declared. So, to avoid such an error, one must pass a constant value while initializing the global variable or pass them 0. So, this is a rule defined by C++ language. If this situation takes place, it will cause this error. So, to fix this type of error, we can declare variables in a function or initialize them with a constant value.

Syntax:

This is not a built-in function or library. So, it does not have a standard function to call it. Instead, it is an error so it will have a message that will be returned if we encounter such error.

error: initializer element is not constant

The above shown is the error message. It might change in some cases but the context of the message will remain the same.

Example # 01:

Now, to get a better hold of this error and to understand this error in more detail we will perform a practical example. To do, so we have initialized global variables “a” and “b”. The value of variable a is initialized to be 100. The value of b is equal to a. This means that whatever the value of a will be it will be the same as the value of b. In our main function, we have printed the value of b with the message “The value of b=”. We have not written any complex code here just to make our point clear. In line 10 we have returned 0 because our main function has an integer as its return type. Now, we will execute our code to see what happens.

#include <iostream>

using namespace std;
int a = 100;
int b = a;
int main()
{
    cout<<«The value of b=»<<b<<endl;

    return 0;
}

After executing our code, we do not have the desired output. Instead of our output, the compiler has given us an error which is «initializer element is not constant». After that, it showed us the code in which the error occurred and that is line number 3. Now, if we recall our code, we initialized the value of integer b in line 3 which means that there is a problem with that piece of code. Let us try to resolve that problem.

To resolve the problem in line 3, we have re-checked our code and we have diagnosed the problem. We discussed earlier in the introduction that this error occurs when we do not declare a variable that we declare globally in our code or do not pass a constant value to it. The same case has occurred here. We have passed the value of integer a to b. The integer a is a variable, not a constant, therefore its value could change, So the compiler has shown us the error.

We have initialized the value of b to 100. After that, we executed the code, and the code was compiled successfully. So, by this example, we have made the point clear that we cannot pass a dynamic value to a global variable.

Example # 02:

This is a little bit complex example as compared to the previous one but the purpose of doing a complex example is to make you understand the error in more detail. To perform it, we have declared four integers that are x, y, z, and i. The values of the x, y, and z variables are 10, 20, and 50 respectively while “i” is an integer that will not be used to perform any operation. But it will be used as an iterator for our loop which we will be using in our main method. We also can declare this integer in our main method, but we found it easy, so we declared it here.

You can declare it in the main function or in a for loop. After that, we declared an integer pointer that is equal to x. In line 6 we have declared an array which is also globally declared and passed it three values because it has a length of 3. In our main method, we have written a loop that will run three times and will print the address of the indexes of the array and the values stored in that index of the array. Now, we will execute our code to see our output.

#include <iostream>

using namespace std;
int a = 10, y = 20, z = 50, i;
int *p = &x;
int *arr[3] = {p, &y, &z};
int main()
{
    for(i = 0; i<3; i++){
        cout<<«Address =»<<arr[i]<<«value =»<<*arr[i]<<endl;
    }

    return 0;
}

After the execution of our code, the compiler has given us the error which means that our code is not compiled successfully. If we take a look at the message of our error, we can see that we have the same error as in the previous example. This time it has occurred in line 6 of our code. If we look at our code and check line 6, we are initializing and declaring our array in line 6. So there has been a mistake in declaring or initializing our array. If we look at the initializing part, we can see that we have passed the variables y and z according to the programming standards, but we have passed x through a pointer. The pointer is not a constant variable and its value might change. So, the code has given an error.

To resolve the error, we will pass the integer x directly and see what happens.

The code has successfully been executed returning the address and values of the indexes of our array.

Conclusion

In this article, we discussed an error which is “Initializer Element is not correct”. We discussed the basics of global variables and how to initialize them according to coding rules and standards. We also performed multiple examples to get this error and resolved them.

About the author

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Sometimes during complex programing, there are chances we make some mistakes during hurry to write and complete the program so that we can test the features, in somewhat similar occasion, we faced an error during compilation as, “error: initializer element is not constant” , now as mentioned, if we have written multiple lines during coding and before compilation, it becomes difficult to remember we initialized which variable and where..?

So, lets recreate similar error, with a very basic C program as below,

 $ vim helloerror.c 
#include <stdio.h>
#include <stdlib.h>

int *var = (int *)malloc(sizeof(int));

int main(int argc, char **argv) {
        *var = 10;
        printf("var is %d\n", *var);
        return 0;
}
 $ gcc -o helloerror helloerror.c 
$ ./helloerror
helloerror.c:4:12: error: initializer element is not constant
 int *var = (int *)malloc(sizeof(int));
            ^

so, we got the mentioned error and during compilation, if the compiler is latest, it also shown the line of error.

Now, if we relooked at the code, we have a global integer pointer “var” and we are assigning a memory to it by calling malloc, ideally this looks OK, but the catch is this is a “GLOBAL” variable, outside all the functions, so the program execution only initialises these variables once, so these are expected to be constants and not changing like we have done an assigned of it to memory returned by malloc.

SO, to avoid this error, always make sure all global variables are assigned with constants.

Now, lets rewrite this program to make sure error is gone,

#include <stdio.h>
#include <stdlib.h>

int *var = NULL;

int main(int argc, char **argv) {
        var = (int *)malloc(sizeof(int));
        *var = 10;
        printf("var is %d\n", *var);
        return 0;
}

Changes are done in “int *var = NULL;” and moving malloc statement inside main.

Follow us on Social Media

Initializer Element Is Not Constant With Code Examples

In this session, we’ll try our hand at solving the Initializer Element Is Not Constant puzzle by using the computer language. The code that follows serves to illustrate this point.

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */
The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

We have shown how to address the Initializer Element Is Not Constant problem by looking at a number of different cases.

What is the error initializer element is not constant?

Solution 1 It’s not inside a function, which means it has to be an initializer – which is assigned only when the item is declared – which means it must be a constant value at compile time, which malloc cannot be.22-Jul-2021

What is not constant in C?

Moreover, in C language, the term «constant» refers to literal constants (like 1 , ‘a’ , 0xFF and so on), enum members, and results of such operators as sizeof . Const-qualified objects (of any type) are not constants in C language terminology.11-Jun-2010

What is the use of initializer list in C++?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.19-Apr-2022

What is a const variable in C?

The const keyword specifies that a variable’s value is constant and tells the compiler to prevent the programmer from modifying it.03-Feb-2022

How do you declare a constant?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.15-Sept-2021

What are the two types of constants?

It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants. Structure, array, pointer, union, etc., are types of secondary constants.

What is constant in C with example?

A constant is a value or variable that can’t be changed in the program, for example: 10, 20, ‘a’, 3.4, «c programming» etc. There are different types of constants in C programming.

How do you initialize an object in C++?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor’s argument list. Using a single initialization value and the = operator.

How do you initialize a data member in C++?

Static Data Member Initialization in C++ We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator, then the variable name.30-Jul-2019

How do you initialize a constant characteristic of a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.30-Jul-2019

Follow us on Social Media

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Inst 08103 04 ошибка ман
  • Initializecomponent c ошибка
  • Insatiable boot device windows 10 ошибка при загрузке
  • Initializeatkacpidevice returns false как исправить ошибку
  • Inst 02987 03 ошибка ман тга

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: