我直到凌晨 1 点才发现我的代码中的一个错误,而我的发现让我感到非常惊讶。实际代码非常复杂,涉及包含结构联合的结构联合等,但我已将问题提炼为以下简化的失败案例。
正在发生的事情是编译器 [gcc 5.4.0] 正在更改指定初始化程序的执行顺序,以匹配它们在结构中出现的顺序。只要您使用没有顺序依赖性的常量或变量初始化结构,这不会导致任何问题。查看以下代码。它表明编译器清楚地重新排序了指定的初始值设定项:
#include <stdio.h>
typedef const struct {
const size_t First_setToOne;
const size_t Second_setToThree;
const size_t Third_setToTwo;
const size_t Fourth_setToFour;
} MyConstStruct;
static void Broken(void)
{
size_t i = 0;
const MyConstStruct myConstStruct = {
.First_setToOne = ++i,
.Third_setToTwo = ++i,
.Second_setToThree = ++i,
.Fourth_setToFour = ++i,
};
printf("\nBroken:\n");
printf("First_setToOne should be 1, is %zd\n", myConstStruct.First_setToOne );
printf("Second_setToThree should be 3, is %zd\n", myConstStruct.Second_setToThree);
printf("Third_setToTwo should be 2, is %zd\n", myConstStruct.Third_setToTwo );
printf("Fourth_setToFour should be 4, is %zd\n", myConstStruct.Fourth_setToFour );
}
static void Fixed(void)
{
size_t i = 0;
const size_t First_setToOne = ++i;
const size_t Third_setToTwo = ++i;
const size_t Second_setToThree = ++i;
const size_t Fourth_setToFour = ++i;
const MyConstStruct myConstStruct = {
.First_setToOne = First_setToOne ,
.Third_setToTwo = Third_setToTwo ,
.Second_setToThree = Second_setToThree,
.Fourth_setToFour = Fourth_setToFour ,
};
printf("\nFixed:\n");
printf("First_setToOne should be 1, is %zd\n", myConstStruct.First_setToOne );
printf("Second_setToThree should be 3, is %zd\n", myConstStruct.Second_setToThree);
printf("Third_setToTwo should be 2, is %zd\n", myConstStruct.Third_setToTwo );
printf("Fourth_setToFour should be 4, is %zd\n", myConstStruct.Fourth_setToFour );
}
int main (int argc, char *argv[])
{
(void)argc;
(void)argv;
Broken();
Fixed();
return(0);
}
输出如下:
Broken:
First_setToOne should be 1, is 1
Second_setToThree should be 3, is 2
Third_setToTwo should be 2, is 3
Fourth_setToFour should be 4, is 4
Fixed:
First_setToOne should be 1, is 1
Second_setToThree should be 3, is 3
Third_setToTwo should be 2, is 2
Fourth_setToFour should be 4, is 4
我怀疑优化器,但我使用每个可能的优化级别尝试了相同的代码,并且重新排序仍然发生。所以这个问题在基础编译器中。
我有一个解决方案,所以这更像是对其他人的警告和一般性问题。
有没有其他人见过或注意到这个问题?
这是预期/指定的行为吗?