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

2

1

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

Armrest answered 8/2, 2013 at 5:13 Comment(3)
Hmm... Strings are allowed to be pooled. So if I had to guess, this might actually be allowed.Khadijahkhai
Essentially, Your question is are objects with static storage duration guaranteed to have unique addresses. The answer is No, the standard does not mandate any such guarantee.Dunkle
Related (though different, due to lack of static): Are const variables required to be distinct in memory?Armrest
B
2

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.

Berber answered 23/5, 2013 at 17:53 Comment(0)
B
1

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.

Beachcomber answered 8/2, 2013 at 5:26 Comment(4)
Can you point to the section of the standard that states that?Armrest
Strictly speaking the only thing that is guaranteed is the result of the equality test; that test is also the only way a program can observe whether two objects are the same or not. This is no accident and stems from the way the C notion of an object is defined.Despicable
@Armrest 6.5.9.8p6, which I didn't know myself but found by googling "must distinct objects have distinct addresses C", the top hit is https://mcmap.net/q/393606/-in-c-are-const-variables-guaranteed-to-be-distinct-in-memoryBeachcomber
Thank you. That answer you linked to is very interesting.Armrest

© 2022 - 2024 — McMap. All rights reserved.