小编Bur*_*ner的帖子

深奥C指定初始化程序失败,编译器错误或功能?

我只花了大约凌晨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 …
Run Code Online (Sandbox Code Playgroud)

c struct initialization designated-initializer

4
推荐指数
1
解决办法
80
查看次数