Search code examples
cinitializationlanguage-lawyerinitializer

Will an ability to select identifier in designator based on the result of constant expression be useful?


C11, 6.7.9 Initialization:

designator:
    [ constant-expression ]
    . identifier

Will an ability to select identifier in designator based on the result of constant expression be useful?

Rationale: if "a constant expression can be evaluated during translation rather than runtime" (6.6 Constant expressions), then its result can be used to provide an ability to select identifier in designator.

Example:

union
{
    float f;
    int   i;
} x = { <constant-expression> ? .f = 1.0f : .i = 0 };

It can be seen as: control the destination types based on the result of constant expression. Otherwise (now) the destination types (i.e. identifier in designator) need to be known in advance.


Solution

  • Will an ability to select identifier in designator based on the result of constant expression be useful?

    As code can already selectively initialize an object, I see little application to OP's new idea to selectively initialize a member.

    typedef union {
      float f;
      int i;
    } fi;
    
    int main() {
      fi x = 0 ? (fi) {.f = 1.0f} : (fi) {.i = 0};
      printf("%f %d\n", x.f, x.i);
      fi y = 1 ? (fi) {.f = 1.0f} : (fi) {.i = 0};
      printf("%f %d\n", y.f, y.i);
      return 0;
    }
    

    Output

    0.000000 0
    1.000000 1065353216