2

Suppose, If I use ternary operator like this: a ? b : c ? d : e

Code :

#include <stdio.h>

int main()
{
    int a=1,b=2,c=3,d=4,e=5;
    printf("%d\n", a ? b : c ? d : e);
    return 0;
}

Gcc and Clang Give an output 2.

Questions:

  • Is it guaranteed to parse as a (a ? b : (c ? d : e))? or
  • Is it unspecified behaviour?
  • What the C standard says about it?
msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

7

The syntax for the ternary operator, also known as a conditional expression, is defined in section 6.5.15 of the C standard as follows:

conditional-expression:

logical-OR-expression
logical-OR-expression ? expression : conditional-expression

Because a "condition-expression" is not a "logical-OR-expression" (read: the logical OR operator has higher precedence) this prevents a ? b : c ? d : e from being parsed as (a ? b : c) ? d : e. This also means that the operator is right-to-left associative with itself. Therefore it gets parsed as a ? b : (c ? d : e).

For more details, you can find the operator precedence rules here. While the standard is the authoritative source, this table lists the rules in a manner that's easier to understand.

As it can be difficult for people to remember the full set of precedence rules, and because different languages sometimes have differing precedence rules, it is best to be explicit about the ordering of operations and use parenthesis to make your intentions more clear to the reader.

dbush
  • 205,898
  • 23
  • 218
  • 273