Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 920
tucuxi Avatar asked Apr 07 '16 14:04

tucuxi


1 Answers

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."

like image 74
Sourav Ghosh Avatar answered Nov 18 '22 20:11

Sourav Ghosh