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

江枫思渺然 提交于 2019-12-08 08:36:33

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14766115/can-constant-objects-with-static-storage-duration-and-equal-constant-initialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!