473,378 Members | 1,444 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Quirk in Conditional Operator?:

mux
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.

Is there any other such odd things (not behavior) in using a conditional
operator I need to be aware of?

For that matter, is there any website that would point to such quirks in c?

Any help would be greatly appreciated.

Regards,
Muralidhar
mu********************@yahoo.com
Nov 14 '05 #1
4 4661
"mux" <mu*@sd.com> wrote in
news:ca**********@charm.magnus.acs.ohio-state.edu:
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);


What happens when you write it for clarity? E.g.

b = a > 10 ? 20 : 30;

Try that. If you are a parenaphile try:

b = (a > 10) ? 20 : 30;

--
- Mark ->
--
Nov 14 '05 #2
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
Nov 14 '05 #3
mux wrote:
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.
Informally speaking, the conditional operator `?:' has
"higher precedence than" or "binds more tightly than" the
assignment operator `='. (More formally, the Standard that
defines the C language specifies a grammar for the language,
and the grouping of operators with operands is a consequence
of the way the grammar is defined. Usually it's easier to
use terms like "precedence" when talking to humans rather
than to parsers.)

Of course, saying that one operator has higher precedence
than another "because it's defined that way" merely avoids
the issue: *Why* is the language defined this way? The answer
is that the inventors chose rules that would lead to "natural-
looking" expressions in the most common cases. The multiplication
operator `*' has higher precedence than the subtraction operator
`-' because people expect `a*b-c' to mean `(a*b)-c' rather than
`a*(b-c)'. The assignment operator `=' has a very low precedence
because people expect `x=a+b' to mean `x=(a+b)' and not `(x=a)+b'.

So: The assignment operator has very low precedence; it
"binds less tightly" than almost all other operators. Your
original statement is therefore understood as

((a>10)?(b=20):b)=30;

.... and now, I suppose, you can understand gcc's complaint:
the thing on the left-hand side of the assignment operator
is not something one can assign to. It's analogous to writing
`x+1=b'.

When you repair the expression by inserting explicit
parentheses, the result is parsed as

(a>10)?(b=20):(b=30);

.... which makes sense. You may be wondering why the middle
set of parentheses wasn't actually required: I've just been
telling you that the assignment in `b=20' has lower precedence
than the conditional operator, which might lead you to think
that your final version would be parsed as

((a>10)?b)=20:(b=30);

.... which is complete nonsense. Well, that's where notions
like "precedence" are too simplistic for a good explanation.
The Standard's grammar is constructed in such a way that this
nonsensical parse is not attempted; the "inner" assignment is
"known" to occur in a context where it must "bind more tightly"
than the `?:'. No such simple escape is possible for the
third sub-expression, though: we're back into "open context."

By the way, the usual form for your statement is something
more like

b = a>10 ? 20 : 30;

.... which once again exhibits the desirability of "low precedence"
for the assignment operator.
Is there any other such odd things (not behavior) in using a conditional
operator I need to be aware of?
I don't know how to answer this, because something that
seems odd to you may seem perfectly normal to me or to anyone
with greater experience of the language. "Oddity is in they
eye of the beholder."
For that matter, is there any website that would point to such quirks in c?


Every web site and every text or reference work on any
subject at all probably contains something that someone would
consider a "quirk." If you can give a rigorous definition of
"quirk" there might be a way to answer the question -- but if
you could give such a definition, you'd probably no longer need
to have the question answered!

--
Er*********@sun.com

Nov 14 '05 #4
Wow...That was one of the most elegant answer I have seen in years.

Thanks for helping me out. and true that Quirk is in the eyes of the
beholder. But I felt that someone might be gracious enough to put a warning
sign for such tiny titbits that would life of a programmer(and a debugger)
much easier.

Thanks once again

Regards
Muralidhar
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
by: bnp | last post by:
Hi, Is possible to use functions in conditional operator as ashown below. ..... ..... int fun1() { // body }
2
by: Robert Jacobson | last post by:
Hi, I'm trying to get a reference to an object in a collection. If the indexer is outside of the range, it should return null, without raising an IndexOutOfRange exception. I'm currently...
6
by: Robert Zurer | last post by:
In his paper on Coding Standard found on http://www.idesign.net/idesign/DesktopDefault.aspx Juval Lowy discourages the use of the ternary conditional operator with no specific reason given. ...
14
by: gupta.keshav | last post by:
Hi, I want to know the trick of implementing condition operator or (if()... else...). Symbols to use: ~, !, ^,&, +, |, <<, >>. NOt to use: if statement, loops,
9
by: Marty | last post by:
Hi, Does using the the conditional operator (?:) instead of the common "if" statement will give a performance gain in a C# .NET 2003 application (even in C# .NET 2005?). What is the advantage...
11
by: junky_fellow | last post by:
Hi guys, I have a piece of code: int func(int flag) { int number=1; if (flag == 1) return 0; if(flag == 2)
5
by: paulo | last post by:
Can anyone please tell me how the C language interprets the following code: #include <stdio.h> int main(void) { int a = 1; int b = 10; int x = 3;
15
by: Dan Henry | last post by:
I have run across functions in the Linux kernel's MTD driver that have me scratching my head a bit. The functions have the general form: extern int bar(size_t len, size_t *retlen, unsigned char...
3
by: somenath | last post by:
Hi All, I have one question regarding the conditional operator. In the draft C99 standard it is mentioned that "1 The following are the sequence points described in 5.1.2.3: -- The call to a...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.