Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 5th, 2007, 9:22 AM   #1
sharadpro
Newbie
 
Join Date: Feb 2006
Location: India
Posts: 25
Rep Power: 0 sharadpro is on a distinguished road
Operator Precedence

Quoting the book Thinking in C++,
while((char c = cin.get()) != 'q')
The addition of the extra parentheses would seem like an innocent
and useful thing to do, and because you cannot use them, the
results are not what you might like. The problem occurs because
‘!=’ has a higher precedence than ‘=’, so the char c ends up
containing a bool converted to char. When that’s printed, on many
terminals you’ll see a smiley-face character.


The author uses while( char c = cin.get() != 'q') to check if the character being input is q and says that extra () can't be used as stated above.

Is it ok? AFAIK , if the () are not used , then it is a problem and not otherwise.If not used , cin.get() != 'q' would be evaluated first and the bool value assigned to char
sharadpro is offline   Reply With Quote
Old Feb 5th, 2007, 12:17 PM   #2
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
I suspect what the author means is:
Quote:
The omission of the extra parentheses would seem like...
Though the whole paragraph is worded rather confusingly.

Suffice to say, boolean operators have a higher precedence than the assignment operator, thus:
x = y != z
Is equivalent to:
x = (y != z)
In other words, x is assigned a boolean value. This is why you have to explicitly bracket the "x = y", when dealing with while loops of this type.
(x = y) != z
Precedence is all about what operators are evaluated first. You may remember from basic math that the multiplication operator has a higher precedence than the addition operator. So this:
x + y * z
Is the same as:
x + (y * z)
Lower precedence operators are evaluated after ones with higher precedence, so multiplication takes place before division. The assignment operator has one of the lowest precedences of all the operators, and thus is evaluated last in the majority of circumstances.
Arevos is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 9:37 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC