Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, when is conditional "test ? : alt" form (empty true case) supported? [duplicate]

Tags:

c

gcc

conditional

In gcc, I can write foo ? : bar which is a shorthand form of foo ? foo : bar but I see that K&R doesn't mention it.

Is this something I should rely on, defined in some standard? Or just an (evil) gcc extension I should avoid?

like image 435
blueshift Avatar asked Jun 08 '12 09:06

blueshift


1 Answers

This is a GCC extension by the name:
Conditionals with Omitted Operands.

It is not standard c.Using -pedantic flag for compilation will tell you so.

The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.

Therefore, the expression

    x ? : y

has the value of x if that is nonzero; otherwise, the value of y.

This example is perfectly equivalent to

    x ? x : y

In this simple case, the ability to omit the middle operand is not especially useful. 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.

Is this something I should rely on, defined in some standard? Or just an (evil) gcc extension I should avoid?

Depends on your requirements, If your code does'nt need to run on any other compiler implementation other than GCC then you can use it. However, if your code is to build on across different other compiler implementations then you should not use it.

Anyhow, One should aim to write as much intuitive and readable code as possible given that I would always suggest avoiding such (ugly)constructs.

like image 106
Alok Save Avatar answered Oct 03 '22 08:10

Alok Save