D
Dan Noland
A friend of mine asked me a C question that I couldn't answer. Could
you guys weigh in?
---------- Forwarded message ----------
Date: Sun, 21 Nov 2004 21:08:27 -0500
From: Rick Kennell <[email protected]>
To: (e-mail address removed)
Subject: abuse of conditional operators
I was pretty bemused a few years ago when I was writing a compiler and
found out that some people expected this to work:
a ? b : c = d;
i.e. if 'a' is non-zero, assign 'd' to 'b', otherwise assign 'd' to 'c'.
Technically, there's no guarantee of support for this since X3J11
specifically claims that the conditional operator does not yield an
lvalue. GCC handles it and modern versions at least warn that this it's
deprecated behavior. TCC silently bungles it. I don't know about other
compilers.
So yesterday, I was reading LKML and came across someone who broke a
code-checking system because something was coded as:
a = b ? : c;
Specifically, the code was:
int tickadj = 500/HZ ? : 1;
which sets tickadj either to 500/HZ or to 1 if HZ is larger than 500.
Effectively, this means that
a = b ? : c;
is equivalent to
a = b ? b : c;
Neither the original K&R nor my copy of X3J11 say nothing about this.
There is a note about it in the GCC documentation
http://gcc.gnu.org/onlinedocs/gcc-3.4.3/gcc/Conditionals.html#Conditionals
but it doesn't say anything about C99. Am I correct in assuming it's
just a GCCism?
Rick
you guys weigh in?
---------- Forwarded message ----------
Date: Sun, 21 Nov 2004 21:08:27 -0500
From: Rick Kennell <[email protected]>
To: (e-mail address removed)
Subject: abuse of conditional operators
I was pretty bemused a few years ago when I was writing a compiler and
found out that some people expected this to work:
a ? b : c = d;
i.e. if 'a' is non-zero, assign 'd' to 'b', otherwise assign 'd' to 'c'.
Technically, there's no guarantee of support for this since X3J11
specifically claims that the conditional operator does not yield an
lvalue. GCC handles it and modern versions at least warn that this it's
deprecated behavior. TCC silently bungles it. I don't know about other
compilers.
So yesterday, I was reading LKML and came across someone who broke a
code-checking system because something was coded as:
a = b ? : c;
Specifically, the code was:
int tickadj = 500/HZ ? : 1;
which sets tickadj either to 500/HZ or to 1 if HZ is larger than 500.
Effectively, this means that
a = b ? : c;
is equivalent to
a = b ? b : c;
Neither the original K&R nor my copy of X3J11 say nothing about this.
There is a note about it in the GCC documentation
http://gcc.gnu.org/onlinedocs/gcc-3.4.3/gcc/Conditionals.html#Conditionals
but it doesn't say anything about C99. Am I correct in assuming it's
just a GCCism?
Rick