Search code examples
cc99language-lawyersentinel

Can constant objects with static storage duration and equal, constant initializers be coalesced?


Consider two objects with static storage duration and equal, constant initializers:

static const int a = 50;
static const int b = 50;

Is it valid for a compiler to combine these such that &a == &b?

(For context, I was thinking of using static constant objects to get unique addresses to use as sentinel pointer values. If it is legal for a compiler to combine such objects and I use the same constant value for two such objects, then the addresses could be equal and I cannot use them as sentinel values.)


Solution

  • The pointers must compare not-equal. See C99 6.5.9 paragraph 6:

    Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.