This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: C Ternary Conditional Expression Last Operand Omission
- From: Jonathan Wakely <jwakely dot gcc at gmail dot com>
- To: "Garreau, Alexandre" <galex-713 at galex-713 dot eu>
- Cc: gcc-help <gcc-help at gcc dot gnu dot org>
- Date: Fri, 16 Mar 2018 23:45:16 +0000
- Subject: Re: C Ternary Conditional Expression Last Operand Omission
- References: <r5jsn0cmt8ln.qyr.xxuns.g6.gal@galex-713.eu>
On 16 March 2018 at 19:30, Garreau, Alexandre wrote:
> Hi,
>
> I was reading the “C Extensions” section of GCC manual [0] about GNU
> extensions, and going through the part about conditional expression
> operand omission, I noticed it said it allowed the omission of the
> *middle* operand (then nicely allowing some construct really similar to
> the lisp or)
>
> But I don’t understand why the analogous omission of the last operand
> with the same semantics (returning the first operand if we need to
> return the omitted one) is not permitted then. It’s not already standard
> nor then supported by gcc, and though the same effect can be obtained by
> negating the first operand, I find usually more expressive to let a
> positive test expression. Also omitting the last instead of the middle
> operand would have seemed more natural to write (as it maybe would have
It seems less natural to me.
"return val ?: alt;" means "if val is good, return it, otherwise some
fallback alternative". This is useful e.g. when val is a pointer and
you want to avoid returning NULL.
"return val ? alt :;" would mean "if val is good, return something
else, otherwise return the value we just decided is not good"
The other reason that "x ? : y" makes more sense is that for scalar
values in C there are many true values (anything non-zero) but only
one false value (zero). If it's any of the true values, return it,
otherwise return false. Whereas with "x ? y :" it would mean if it's
any true value, return a specific value (losing the original value of
x) otherwise return x (which we know must be zero in this case).
When you're using the extension to avoid evaluating an operand twice
(as explained in the manual) "x ? : y" serves a useful purpose. Your
suggestion doesn't add anything, because you can just write "x ? y :
0" to avoid evaluating x twice.
> allowed to omit the colon too, if I’m not wrong about something
> conflicting with it in C syntax, as it would simplify syntax and allow
> more non-simply-erroneous combinations of syntax).
>
> Is there any justification to that? was it just considered as
> unnecessary? Was this form considered less useful? was a feature
> looking alike lisp or considered more evidently useful?
>
> Should I ask on the main gcc list?
>
> [0] (info "(gcc-6) C Extensions")
> [1] (info "(gcc-6) Conditionals")