Strange values while initializing array using designated initializers

前端 未结 5 1070
迷失自我
迷失自我 2021-02-07 05:57

When I initialize the array below all the output looks ok except for values[3]. For some reason values[3] initialized as values[0]+values[5]

5条回答
  •  盖世英雄少女心
    2021-02-07 06:10

    This has nothing to do with designated initializers as such. It is the same bug as you'd get when attempting something like this:

    int array[10] = {5, array[0]};
    

    The order in which initialization list expressions are executed is simply unspecified behavior. Meaning it is compiler-specific, undocumented and should never be relied upon:

    C11 6.7.9/23

    The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified.

    Since you are using array items to initialize other array members, it means that you must change your code to run-time assignment instead of initialization.

      int values[10];
    
      values[2] = -100;
      values[5] = 350;
      values[3] = values[0] + values[5];
      ...
    

    As a side-effect, your program will now also be far more readable.

提交回复
热议问题