473,763 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.c om
Nov 14 '05 #1
4 4688
"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.hel sinki.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
2167
by: bnp | last post by:
Hi, Is possible to use functions in conditional operator as ashown below. ..... ..... int fun1() { // body }
2
1270
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 using the conditional operator to do this, which is rather kludgy: TreeNode currentNode = i < nodes.Count ? nodes : null;
6
2989
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. I can understand that complicated code would be much less readable using nested operators, but aside from that is there another reason? -- something going on under the hood perhaps which make it inadvisable to use?
14
2226
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
4783
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 of using it in C# other than typing shorter if ? Thanks, Marty
11
3202
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
2904
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
5213
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 *buf); int foo(size_t len, unsigned char *buf) { size_t retlen; int ret; ret = bar(len, &retlen, buf);
3
2477
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 function, after the arguments have been evaluated (6.5.2.2). -- The end of the first operand of the following operators: logical AND && (6.5.13);
0
9389
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10149
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9943
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9828
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8825
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5271
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3918
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.