I’m working with some memory pointers. I don’t want to use hash defines, please leave that discussion aside. I would just like to know why this does not compile:
#include <stdio.h>
static const unsigned long *const pMemAddrA = (unsigned long *) 0x00000200ul;
static const unsigned long *const pMemAddrB = pMemAddrA;
int main (void)
{
printf("%x", (unsigned int) pMemAddrB);
return 0;
}
Compiler output gcc:
||=== TestConst, Debug ===|
...main.c|4|error: initializer element is not constant|
||=== Build finished: 1 errors, 0 warnings ===|
EDIT:
After reading the answers, I’m happy to know how to go about this problem.
However I do not understand why it is a problem. From what I know static memory gets allocated at program start. I know there is issue if variables “live” in different files and the order in which the variables are allocated cannot be guaranteed by the compiler. However, if both variables “live” in the same file – just as both variables living in the same function – I would think the compiler can assure that memory gets allocated in the order of variables being declared in the file, and therefore I don’t understand why declaring and initializing a const pointer to another const pointer is an issue. I’d be happy if someone could enlighten me.
Your pointers have file scope, so the initialisers must be constant expressions.
pMemAddrAisn’t a constant expression, therefore can’t be used to initialise a variable with static storage.It can be used to initialise a variable in block scope, so if you move your declarations inside
main(and make at least the second non-static), it will compile:If the two pointers must be declared at file scope, there is no way to prevent either repeating the initialising expression,
or
#defineing it.