473,396 Members | 2,085 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,396 software developers and data experts.

Comparison with single '='?

In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:

#include <iostream.h>
int result; // the result of the calculations
char oper_char; // the user-specified operator
int value; // value specified after the operator
int main()
{
result = 0; // initialize the result
// Loop forever (or till we hit the break statement)
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
cin >oper_char;
cin >value;
if (oper_char = '+')
result += value;
} else {
cout << "Unknown operator " << oper_char << '\n';
}
}
return (0);
}

In the if statement only one '=' is used:

if (oper_char = '+')

Should that not be '==' or is there some exception in C++ where you can
compare chars with only '='?

Later in the text they type 'if (oper_char = '+')' again so it seems
that its not a typo - unless the O'Reilly author has been in a rush.
Apr 19 '07 #1
8 1429
On Thu, 19 Apr 2007 14:58:51 +0200, Johs wrote:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:

#include <iostream.h>
int result; // the result of the calculations
char oper_char; // the user-specified operator
int value; // value specified after the operator
int main()
{
result = 0; // initialize the result
// Loop forever (or till we hit the break statement)
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
cin >oper_char;
cin >value;
if (oper_char = '+')
result += value;
} else {
cout << "Unknown operator " << oper_char << '\n';
}
}
return (0);
}

In the if statement only one '=' is used:

if (oper_char = '+')

Should that not be '==' or is there some exception in C++ where you can
compare chars with only '='?

Later in the text they type 'if (oper_char = '+')' again so it seems
that its not a typo - unless the O'Reilly author has been in a rush.
Not having read the book myself, I would say it is almost certainly a
typo. '=' is assignment, never comparison (theoretically, a class could
overload '=' to mean comparison, but this is a Really Bad Thing and is not
done here).

There are times to use an '=' in the expression of an if or while
statement, but it's essentially useless to do so when the right-hand side
is a constant.

- Michael
Apr 19 '07 #2
On Apr 19, 2:58 pm, Johs <asd...@asd.comwrote:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:

#include <iostream.h>
http://www.parashift.com/c++-faq-lit....html#faq-27.4
int result; // the result of the calculations
char oper_char; // the user-specified operator
int value; // value specified after the operator
int main()
{
result = 0; // initialize the result
// Loop forever (or till we hit the break statement)
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
cin >oper_char;
cin >value;
if (oper_char = '+')
Looks like a "{" is missing here.
result += value;
} else {
cout << "Unknown operator " << oper_char << '\n';
}
}
return (0);

}

In the if statement only one '=' is used:

if (oper_char = '+')

Should that not be '==' or is there some exception in C++ where you can
compare chars with only '='?
Yes this should be '=='.

Using '=' here means to have always the same condition
in the if statement. Which in turn means that the
if statement is omissible.
HTH

Apr 19 '07 #3
On Apr 19, 8:58 am, Johs <asd...@asd.comwrote:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:

#include <iostream.h>
#include <iostream>
int result; // the result of the calculations
char oper_char; // the user-specified operator
int value; // value specified after the operator
int main()
{
result = 0; // initialize the result
// Loop forever (or till we hit the break statement)
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
cin >oper_char;
cin >value;
if (oper_char = '+')
result += value;
} else {
cout << "Unknown operator " << oper_char << '\n';
}
}
return (0);

}

In the if statement only one '=' is used:

if (oper_char = '+')

Should that not be '==' or is there some exception in C++ where you can
compare chars with only '='?

Later in the text they type 'if (oper_char = '+')' again so it seems
that its not a typo - unless the O'Reilly author has been in a rush.
That needs to be == as already mentioned.
There is a way to insure that the correct operator is employed:

if( 'x' == oper_char )
{
...
}

Looks silly (at first) but effective.
Apr 19 '07 #4
On Apr 20, 12:58 am, Johs <asd...@asd.comwrote:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:
This is a dreadful code example. Assuming you have typed it out
correctly, the book should be called "Practically Useless C++
Programming". Almost every single line is wrong.
#include <iostream.h>
No such standard header, and never has been. You can get the
intended effect by putting the following two lines:
#include <iostream>
using namespace std;
int result; // the result of the calculations
It's called "result" and it will have the result? I never would have
guessed!
char oper_char; // the user-specified operator
int value; // value specified after the operator
More worse-than-useless commentary.
int main()
{
result = 0; // initialize the result
'result' has already been initialized to 0 (by virtue of being
declared outside
of any function). If the author insists on some policy of always
writing an
explicit initializer, then the line should be:

int result = 0;

and it should either be outside the function or inside it (preferably
the latter)
but not both.
// Loop forever (or till we hit the break statement)
There is no break statement.
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
Because a '\n' is not sent to the stream, this text may not appear
yet.
cin >oper_char;
cin >value;
There is no test for failure here.
if (oper_char = '+')
This sets oper_char to be '+', as you noted, and always succeeds.
result += value;
Causes undefined behaviour if there was an error inputting 'value', as
'value' has not yet been assigned a proper value.
} else {
cout << "Unknown operator " << oper_char << '\n';
}
}
This loop has no possible exit condition.
Further, if the user presses the end-of-file character the program
will
output stuff indefinitely without waiting for any further input.
return (0);
These brackets are superfluous.
}
Apr 22 '07 #5
Old Wolf wrote:
>int main()
{
result = 0; // initialize the result

'result' has already been initialized to 0 (by virtue of being
declared outside of any function).
Also, technically, this isn't initialization, but assignment.
> while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";

Because a '\n' is not sent to the stream, this text may not appear
yet.
That's actually not true. cin and cout are tied together, which means that
whenever you read from cin, cout gets automatically flushed.
Also, a '\n' might or might not flush the stream, depending on its buffering
scheme. That's why there is std::endl, which sends a '\n' _and_ flushes the
stream.
> cin >oper_char;
cin >value;

There is no test for failure here.
Right. If the user enters a wrong character, the program will stay in its
endless loop, but ignore all further input.
> if (oper_char = '+')

This sets oper_char to be '+', as you noted, and always succeeds.
> result += value;

Causes undefined behaviour if there was an error inputting 'value', as
'value' has not yet been assigned a proper value.
But 'value' is a global variable. If the error happens during the first loop
iteration, it should be zero, otherwise it should contain the value of the
previous iteration. So I'd say no undefined behavior.

Apr 23 '07 #6
In article <11**********************@e65g2000hsc.googlegroups .com>,
ol*****@inspire.net.nz says...
On Apr 20, 12:58 am, Johs <asd...@asd.comwrote:
In Pratical C++ Programming by Steve Oualline (O'Reilly) I found this
code example:

This is a dreadful code example. Assuming you have typed it out
correctly, the book should be called "Practically Useless C++
Programming". Almost every single line is wrong.
#include <iostream.h>

No such standard header, and never has been. You can get the
intended effect by putting the following two lines:
#include <iostream>
using namespace std;
The OP doesn't seem to specify, but _if_ he's looking at the first
edition of the book, we should probably cut it a break on this
particular one -- the first edition seems to carry a 1995 copyright
date, and at that time the now-standard headers were still quite new.

[ ... ]
while (1) {
I would have added that the canonical "loop forever" is 'for (;;)' --
though I'd also mention that I rarely find this construct useful. With
some thought and care, the (normal) exit condition for a loop can nearly
always be put where it belongs.
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";

Because a '\n' is not sent to the stream, this text may not appear
yet.
cin >oper_char;
According to $27.3.1/2, cin is tied to cout by default, so at this
point, the output above must be displayed. IOW, the program is perfectly
fine in this particular respect.

[ ... ]
return (0);

These brackets are superfluous.
These specific brackets are normally called parentheses.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Apr 23 '07 #7
On Apr 23, 12:23 am, Old Wolf <oldw...@inspire.net.nzwrote:
On Apr 20, 12:58 am, Johs <asd...@asd.comwrote:
#include <iostream.h>
No such standard header, and never has been.
There was when I started using C++. It was, in fact, the de
facto standard up until the promulagation of C++98 (Sept. 1998),
and even some time afterwards, until all of the libraries got
updated. So depending on the date of the book... (Some of the
best and most essential C++ books I have use it, e.g. Barton and
Nackman.)
You can get the
intended effect by putting the following two lines:
#include <iostream>
using namespace std;
That might be sufficient with most implementations, for what
he's doing, but the effect is considerably different. The
standard iostream are NOT compatible with the classic iostream;
there are many subtle differences. And of course, while most
implementations do accept it, as an extension, <iostream>
doesn't declare any of the << operators.

[...]
while (1) {
cout << "Result: " << result << '\n';
cout << "Enter operator and number: ";
Because a '\n' is not sent to the stream, this text may not appear
yet.
Are you sure? C++ doesn't have the concept of a line
synchronized buffer, so the presence or absence of a '\n' is
irrelevant. On the other hand, IIRC, cout is tied to cin, which
means that any input on cin (like that in the following line)
will cause cout to be flushed. (Note that this can cause
reading from cin to be significantly slower than reading from an
ifstream. In non interactive programs, it may be worth
resetting the tie.)

(For the rest, I agree with your evaluation. If the code is
really verbatim out of the book, then it really should be
avoided. Which is rather surprising for O'Reilly.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 23 '07 #8
James Kanze wrote:
And of course, while most
implementations do accept it, as an extension, <iostream>
doesn't declare any of the << operators.
As of last week, it does. Well, for implementations of C++0x.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 23 '07 #9

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

Similar topics

1
by: David Pratt | last post by:
I have been using the following for sorting a list of dictionaries. This works but only provides sorting on a single key. I am wanting to extend this with a better comparison expression so that it...
7
by: rickle | last post by:
I'm trying to compare sun patch levels on a server to those of what sun is recommending. For those that aren't familiar with sun patch numbering here is a quick run down. A patch number shows...
3
by: Tom Timmermann | last post by:
In the process of building a link list, I noticed that successive calls to malloc() return a pointer address that keeps getting larger. Can I always count on this behavior and so do pointer...
3
by: Chandu | last post by:
Hi, I am working on awk programming which is similar to C programming and have got a doubt about time function returning a float value. Ex: 01:01:30 should return 61.5 when i have tried my way i...
37
by: spam.noam | last post by:
Hello, Guido has decided, in python-dev, that in Py3K the id-based order comparisons will be dropped. This means that, for example, "{} < " will raise a TypeError instead of the current...
43
by: michael.f.ellis | last post by:
The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In...
14
by: Steve Bergman | last post by:
I'm looking for a module to do fuzzy comparison of strings. I have 2 item master files which are supposed to be identical, but they have thousands of records where the item numbers don't match in...
11
by: Andrus | last post by:
I created dynamic extension methods for <= and < SQL comparison operators: public static IQueryable<TLessThanOrEqual<T>(this IQueryable<Tsource, string property, object value); public static...
1
by: AllBeagle | last post by:
Hello Everyone, I'm trying to build a web-based application for a client of mine and I keep finding holes in my design, so I could use some guidance if anyone has any to offer. Let me try to...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...
0
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...
0
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,...
0
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...
0
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...

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.