Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C error: "initializer element is not constant" with &, works with +

With GCC I get the "initializer element is not constant" error for the second line of the following code:

uint8_t gBuffer[512 + 4]; /* Data buffer */
uint8_t* gAlignedBuffer = (uint8_t*)(((uint32_t)gBuffer + 4) & 0xFFFFFFFCU);   /* Align buffer to 4-byte boundary */ 

However if I change & 0xFFFFFFFCU to + 0xFFFFFFFCU the code compiles ok:

uint8_t gBuffer[512 + 4]; /* Data buffer */
uint8_t* gAlignedBuffer = (uint8_t*)(((uint32_t)gBuffer + 4) + 0xFFFFFFFCU);   /* Align buffer to 4-byte boundary */ 

Why is this?

like image 262
Anguel Avatar asked Jun 28 '13 14:06

Anguel


People also ask

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.

Which 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.

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.


1 Answers

Apparently you are declaring your variables in file scope. File scope variables have static storage duration and require constant initializers.

While your initializers don't exactly satisfy the most strict and narrow definition of address constant expression (as defined in the languages specification), they might still be supported by your specific compiler. The inconsistency you observe has no real reason to exist though. I'd guess that this is a quirk of that specific compiler.

like image 190
AnT Avatar answered Oct 22 '22 16:10

AnT