somenath said:
I have one doubt regarding the compilation error for the bellow
mentioned code.
#include<stdio.h>
int main(void)
{
int a =5,b=0;
a>5?b=3:b=5;
printf("\n Value of B = %d \n",b);
return 0;
}
Compilation Error
tarnarytest.c: In function `main':
tarnarytest.c:5: invalid lvalue in assignment.
Could any body tell me why is it throwing this error ?
The biggest problem with the line
a>5?b=3:b=5;
isn't that it's illegal, it's that it's *ugly*. Whatever you're
trying to do, there's certainly a better and more legible way to do
it.
For starters, adding whitespace around operators can make things much
easier to read:
a > 5 ? b = 3 : b = 5;
Well, it usually does, but in this case it doesn't help all that much.
What you really need is parentheses.
The key thing here is that the trinary '?:' operator binds more
tightly than the assignment operator. I *think* that the above is
equivalent to:
(a > 5 ? b = 3 : b) = 5;
which attempts to use a conditional expression as the left side of an
assignment. Since the result of a conditional expression is not an
lvalue, this is illegal.
I think what you're trying to do is:
(a > 5) ? (b = 3) : (b = 5);
so adding the parentheses as I've done here is one solution. A slightly
better solution is:
b = (a > 5 ? 3 : 5);
but an even better one is:
if (a > 5) {
b = 3;
}
else {
b = 5;
}
If you insist, you can omit the braces:
if (a > 5)
b = 3;
else
b = 5;
but that can cause problems if you later find that you need to add
more statements.
C has more than a dozen levels of operator precedence. Just by using
an 'if' statement, you avoid having to worry about *any* of them, and
you get code whose meaning is obvious at a glance.
If you're using the '?:' operator where an 'if' statement would do the
job just as well, use an 'if' statement. If you're using multiple
operators in an expression and you're not certain of the precedence,
add parentheses until it's clear what the expression actually means.
I wouldn't bother with parentheses in
a = b + c * d;
but if I have to look up the precedence in a book, the expression is
too obscure. There is no virtue in obfuscation (unless you're
entering the International Obfuscated C Code Contest; see
<
http://www.ioccc.org/>).
There are cases where you actually need to use '?:' rather than 'if',
particularly where you need an expression rather than a statement in a
macro definition. But even in that case, clarity is still important.