mux <mu*@sd.com> scribbled the following:
Hi
I found out that the following piece of code throws an error.
1 #include "stdio.h"
2
3 int main()
4 {
5 int a,b;
6 a= 10;
7 a>10?b=20:b=30;
8 printf("%d",b);
9 }
and the error was:
$ gcc -g -o test test.c
test.c: In function `main':
test.c:7: error: invalid lvalue in assignment
However, when you rewrite line 7 as:
a>10?b=20:(b=30);
Then there is no error. Why it is so? I thought conditional operators where
an macro-like replacement of a simple if-else statement.
They're nothing of the sort. The conditional operator is a real, kosher,
all-singing, all-dancing C operator with C semantics. Thus, it must obey
C rules about operator precedence and lvalues.
In an assignment operation, the RHS must be a modifiable lvalue, and I
don't think the conditional operator produces such things. If I know my
precedence rules, what you are doing is equivalent to:
(a>10 ? (b=20) : b) = 30;
which won't work. However I think you meant:
(a>10) ? (b=20) : (b=30);
Note that you can't do this:
(a<10 ? a : b) = 30;
but you can do this:
*(a<10 ? &a : &b) = 30;
because the unary * (indirect through) operator turns rvalues of type
"pointer-to-T" into modifiable lvalues of type "T".
--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\--
http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The day Microsoft makes something that doesn't suck is probably the day they
start making vacuum cleaners."
- Ernst Jan Plugge