简体   繁体   English

具有静态存储持续时间的常量对象和相等的常量初始值设定项是否可以合并?

[英]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 ? 编译器是否有效组合这些&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.) (对于上下文,我正在考虑使用静态常量对象来获取用作sentinel指针值的唯一地址。如果编译器合并这些对象是合法的,并且我对两个这样的对象使用相同的常量值,那么地址可以是平等的,我不能将它们用作哨兵价值。)

The pointers must compare not-equal. 指针必须比较不相等。 See C99 6.5.9 paragraph 6: 见C99 6.5.9第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. 两个指针比较相等,当且仅当两个都是空指针时,两者都是指向同一对象的指针(包括指向对象的指针和开头的子对象)或函数,两者都是指向同一数组的最后一个元素的指针对象,或者一个指向一个数组对象末尾的指针,另一个是指向紧跟在地址空间中第一个数组对象之后的另一个数组对象的开头的指针。

No, the standard forbids that. 不,标准禁止这样做。 Distinct objects must have distinct addresses. 不同的对象必须具有不同的地址。 In const char a[]="abc", b[]="abc"; const char a[]="abc", b[]="abc"; , a and b are allocated at different addresses. ab分配在不同的地址。 This is also true if they're pointers: in const char *a="abc", *b="abc", a and b` are also allocated at different addresses; 如果它们是指针也是如此:在const char *a="abc", *b="abc", a and b`也分配在不同的地址; the string constant they point to can be a single constant array, just as if it was a named object. 它们指向的字符串常量可以是单个常量数组,就像它是一个命名对象一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM