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

In GCC, I get the error "initializer element is not constant" 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 normally:

 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?

+7
source share
3 answers

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

Although your initializers do not exactly satisfy the most stringent and narrowest definition of an address constant expression (as defined in the language specification), they can still be supported by your specific compiler. The mismatch that you observe has no real reason to exist. I guess this is the quirk of this particular compiler.

+2
source

Since these variables are the file realm, they have static storage, so the behavior is because relocations supports the output file format (I assume this is ELF).

In principle, in this case, ELF objects support adding any number to an unknown address, but do not apply a mask (which the & operation basically does). You will need to move the second statement to the function.

+2
source

My suspicion is that something is happening with the operator priority here. and higher priority than +.

-one
source

All Articles