Search code examples
cgccconditional-operator

How does the ternary C operator interpret an empty 1st branch? Why?


This seems to compile and run without warnings using gcc -Wall (4.9.2)

#include <stdio.h>
int main(int argc, char **argv){
    printf("%d\n", argc-1?:42);
    return 0;
}

If I run it

  • with 0 args (making argc-1 evaluate to false), it prints 42;
  • with n>=1 args (making argc-1 evaluate to true), it prints n-1.

Am I right if I assume that x?:y is in this case equivalent to x?x:y? Is this standard, expected behaviour, or just a GCC quirk?


Solution

  • That's a known gcc extension for the shorthand version of the conditional operator.

     argc-1?:42
    

    is just the same as

    (argc-1)?(argc-1):42
    

    The reason for using this variation is (and I Quote)

    "When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it."