Question

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

Was it helpful?

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.

OTHER TIPS

No, the standard forbids that. Distinct objects must have distinct addresses. In const char a[]="abc", b[]="abc";, a and b are allocated at different addresses. This is also true if they're pointers: in const char *a="abc", *b="abc",aandb` are also allocated at different addresses; the string constant they point to can be a single constant array, just as if it was a named object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top