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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With