Ternary operator during array initialization

Is the tenary operator used inside array initialization with constants valid C99?

uint8_t foo[] = {bar? 9U:20U};
+6
source share
2 answers

Yes, you can. Starting with the production of grammar for the initializer:

6.7.8 Initialization

initializer:
       assignment-expression
       { initializer-list }
       { initializer-list , }
initializer-list:
       designation(optional) initializer
       initializer-list , designation(optional) initializer

The only relevant (in my opinion) restriction on the initializer in this section is that it should be a constant expression for objects with static storage duration:

All expressions in the initializer for an object that has a static storage duration are constant expressions or string literals.

Following him to production assignment-expression, we see that

6.5.16 Assignment Operators

assignment-expression:
        conditional-expression
        unary-expression assignment-operator assignment-expression

. , . , .

6.6

constant-expression:
         conditional-expression

:

, , , - , , , .

. :

  • ,
  • ,
  • .

, :

#include <stdint.h>
#include <stdlib.h>

#define BAR 1

uint8_t foo[] = {BAR ? 9U:20U};

int main(void) {
   int bar = rand();
   uint8_t foo[] = {bar ? 9U:20U};
}

, . .

+7

. clang:

example.c:4:15: warning: initializer for aggregate is not a compile-time
      constant [-Wc99-extensions]
        int foo[] = {bar? 9U:20U};
                     ^~~~~~~~~~~
+2

All Articles