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

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • Hmm... Strings are allowed to be pooled. So if I had to guess, this might actually be allowed. – Mysticial Feb 08 '13 at 05:15
  • 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. – Alok Save Feb 08 '13 at 05:19
  • 1
    Related (though different, due to lack of `static`): [Are `const` variables required to be distinct in memory?](http://stackoverflow.com/q/6236762) – icktoofay Feb 08 '13 at 05:48

2 Answers2

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
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.

jthill
  • 55,082
  • 5
  • 77
  • 137
  • Can you point to the section of the standard that states that? – icktoofay Feb 08 '13 at 05:27
  • 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. – Luc Danton Feb 08 '13 at 05:40
  • @icktoofay 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 http://stackoverflow.com/a/6237094/1290731 – jthill Feb 08 '13 at 05:44
  • Thank you. That answer you linked to is very interesting. – icktoofay Feb 08 '13 at 05:49