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?
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.
This is a GCC extension. It's not part of the C standard, but the GCC compiler lets you use it. See its documentation for details, and be mindful of its behavioural differences to the "equivalent" ternary expression.
This is an extension included in GCC.
It will not work if compiling with another compiler (that does not support that extension).
So I would recommend to avoid using this type of shortcut.
EDIT: As @KevinCox pointed out, even a DEFINE
would not work (see 2nd comment below).