473,671 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

equality operator question

Is it now common practice to use conditional statements like

if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)

over the more traditional statements like

if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)

for all types of 'i' (PODs and classes)?

Jun 27 '08 #1
41 1589
On Sun, 4 May 2008 22:40:28 -0400, "barcarolle r"
<ba*********@mu sic.netwrote in comp.lang.c++:
Is it now common practice to use conditional statements like

if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)

over the more traditional statements like

if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)

for all types of 'i' (PODs and classes)?
The reason for writing the constant first in an equality comparison is
quite simple. A fairly common typographical error is type only one
'=' once in a while when two are intended, and needed.

Consider the implications of accidentally typing:

if (i = 0)

....when you meant to type:

if (i == 0)

Assuming a built-in type, or even a class type having an assignment
operator accepting an int, then the first version, the type, is not
only always false, but it also destroys the existing value of 'i'. Yet
it is syntactically correct and swallowed by the compiler without
complaint.

On the other hand, if you accidentally type "if (0 = i), the compiler
will emit a diagnostic and reject it.

So it is a very inexpensive method of catching a typing error on the
very first compile. This is not an extremely common error, but is one
which happens to everyone once in a while. And of course it doesn't
help when you are comparing two objects, but comparisons with a
constant are fairly frequent.

Some programmers consider it hideously ugly and refuse to ever use it.
I think it is useful and I use it. It works, and it saves time when
you do happen to make that typo.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Jun 27 '08 #2
Jack Klein wrote:
On Sun, 4 May 2008 22:40:28 -0400, "barcarolle r"
<ba*********@mu sic.netwrote in comp.lang.c++:
>Is it now common practice to use conditional statements like

if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)

over the more traditional statements like

if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)

for all types of 'i' (PODs and classes)?

The reason for writing the constant first in an equality comparison is
quite simple. A fairly common typographical error is type only one
'=' once in a while when two are intended, and needed.

Consider the implications of accidentally typing:

if (i = 0)

...when you meant to type:

if (i == 0)

Assuming a built-in type, or even a class type having an assignment
operator accepting an int, then the first version, the type, is not
only always false, but it also destroys the existing value of 'i'. Yet
it is syntactically correct and swallowed by the compiler without
complaint.

On the other hand, if you accidentally type "if (0 = i), the compiler
will emit a diagnostic and reject it.

So it is a very inexpensive method of catching a typing error on the
very first compile. This is not an extremely common error, but is one
which happens to everyone once in a while. And of course it doesn't
help when you are comparing two objects, but comparisons with a
constant are fairly frequent.

Some programmers consider it hideously ugly and refuse to ever use it.
I think it is useful and I use it. It works, and it saves time when
you do happen to make that typo.
I agree, but my compiler warns me if an assignment is being made inside an
if statement. Otherwise I probably would use that format. But since it
does, I stick with the more traditional if ( variable == value )

--
Jim Langston
ta*******@rocke tmail.com
Jun 27 '08 #3

"Jim Langston" <ta*******@rock etmail.comwrote in message
news:wM******** *******@newsfe0 5.lga...
Jack Klein wrote:
<...>
>The reason for writing the constant first in an equality comparison is
quite simple. A fairly common typographical error is type only one
'=' once in a while when two are intended, and needed.

Consider the implications of accidentally typing:

if (i = 0)

...when you meant to type:

if (i == 0)

Assuming a built-in type, or even a class type having an assignment
operator accepting an int, then the first version, the type, is not
only always false, but it also destroys the existing value of 'i'. Yet
it is syntactically correct and swallowed by the compiler without
complaint.

On the other hand, if you accidentally type "if (0 = i), the compiler
will emit a diagnostic and reject it.

So it is a very inexpensive method of catching a typing error on the
very first compile. This is not an extremely common error, but is one
which happens to everyone once in a while. And of course it doesn't
help when you are comparing two objects, but comparisons with a
constant are fairly frequent.

Some programmers consider it hideously ugly and refuse to ever use it.
I think it is useful and I use it. It works, and it saves time when
you do happen to make that typo.

I agree, but my compiler warns me if an assignment is being made inside an
if statement. Otherwise I probably would use that format. But since it
does, I stick with the more traditional if ( variable == value )

Of course to address the problem effectively one could simply *replace* the
offending operators:

#define IS_EQUAL_TO ==

#define INITIALISE_WITH =

#define PLUS +

#define OUTPUT <<

#define CONTENTS_OF *

#define POINTER *

#define ADDRESS_OF &

#include <iostream>

int main()

{

int x INITIALISE_WITH 1;

int POINTER px INITIALISE_WITH ADDRESS_OF x;

if ( CONTENTS_OF px PLUS 1 IS_EQUAL_TO 2){

std::cout OUTPUT "Who needs operators?\n";

}

}

regards

Andy Little


Jun 27 '08 #4
On May 5, 4:40 am, "barcarolle r" <barcarol...@mu sic.netwrote:
Is it now common practice to use conditional statements like
if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)
over the more traditional statements like
if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)
for all types of 'i' (PODs and classes)?
No. First of all, you never compare with true or false. As for
the others, I'd say that it is generally universal practice to
put the constant to the right of the comparision operator. I
don't know where this practice originated, but it certainly
predates C++, and there's no reason to do otherwise in C++.

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

Jun 27 '08 #5
James Kanze <ja*********@gm ail.comwrites:
On May 5, 4:40 am, "barcarolle r" <barcarol...@mu sic.netwrote:
>Is it now common practice to use conditional statements like
> if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)
>over the more traditional statements like
> if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)
>for all types of 'i' (PODs and classes)?

No. First of all, you never compare with true or false. As for
the others, I'd say that it is generally universal practice to
put the constant to the right of the comparision operator. I
don't know where this practice originated, but it certainly
predates C++, and there's no reason to do otherwise in C++.
The reason is that if you have a normal keyboard, without rebound,
you'll type:

if (i = -1) ...

and then the compilers won't complain and will generate:

{ i=-1;
... }

On the other hand, if you write:

if (-1 = i) ...

since -1 is not a LHS, -1=i is invalid and the compilers will signal
an error.
However, I cannot say that's it's common practice.
I prefer to write if(i==-1)...
and I just insert a grep in my makefiles to catch any assignment in
if, while or do conditionals.

--
__Pascal Bourguignon__
Jun 27 '08 #6
On May 5, 3:28 pm, p...@informatim ago.com (Pascal J. Bourguignon)
wrote:
James Kanze <james.ka...@gm ail.comwrites:
On May 5, 4:40 am, "barcarolle r" <barcarol...@mu sic.netwrote:
Is it now common practice to use conditional statements like
if (0 == i)
if (-1 == i)
if (true == i)
if (5 == i)
over the more traditional statements like
if (i == 0)
if (i == -1)
if (i == true)
if (i == 5)
for all types of 'i' (PODs and classes)?
No. First of all, you never compare with true or false. As for
the others, I'd say that it is generally universal practice to
put the constant to the right of the comparision operator. I
don't know where this practice originated, but it certainly
predates C++, and there's no reason to do otherwise in C++.
The reason is that if you have a normal keyboard, without rebound,
you'll type:
if (i = -1) ...
and then the compilers won't complain and will generate:
{ i=-1;
... }
First, of course, I won't generally type that; I'll type:
if ( i == -1 ) ...
(with lot's of white space, so it's easy to see what each token
is). Second, if I do slip up, most compilers will warn, and of
course, the code will never get through code review, nor pass
any of the unit tests. So it's not really a big thing.
On the other hand, if you write:
if (-1 = i) ...
since -1 is not a LHS, -1=i is invalid and the compilers will
signal an error.
Which only works if you're comparing with a constant. On the
other hand, if I write:
if ( f() == x ) ...
rather than
if ( x == f() ) ...
I get the added check with the more natural form. So you force
an unnatural form to occasionally get the check, and more often
to not get it when you otherwise would.
However, I cannot say that's it's common practice.
I prefer to write if(i==-1)...
and I just insert a grep in my makefiles to catch any
assignment in if, while or do conditionals.
Automated code review:-). Definitely a good idea.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #7
On 5 touko, 16:19, James Kanze <james.ka...@gm ail.comwrote:
First of all, you never compare with true or false.
I'm doing that. What could go wrong?
Jun 27 '08 #8
Krice <pa****@mbnet.f iwrites:
On 5 touko, 16:19, James Kanze <james.ka...@gm ail.comwrote:
>First of all, you never compare with true or false.

I'm doing that. What could go wrong?
Well, with false, not much wrong, since false must be == !true, and
if(false){this; }else{that;} must evaluate that, we're about certain
that false == 0.

But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.

But in any case, it's harder to read boolean expression when you add
equivalences with the constants.

Compare:
Is it true that it is false that you're not big?
if(true==(false ==(not(you->big())))){ fast();}

Are you big?
if(you->big()){ fast();}
Ok, even if you remove some == and some not, it's still harder to
understand the question:

Is it true that you're big?
if(true==you->big()){ fast();}

--
__Pascal Bourguignon__
Jun 27 '08 #9
On 2008-05-05 10:48:06 -0400, Krice <pa****@mbnet.f isaid:
On 5 touko, 16:19, James Kanze <james.ka...@gm ail.comwrote:
>First of all, you never compare with true or false.

I'm doing that. What could go wrong?
Not much. But what's the point? The compiler does it. And, more
important, where do you stop?

if (a)
if (a == true)
if ((a == true) == true)
if (((a == true) == true) == true)

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

Jun 27 '08 #10

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

Similar topics

1
1566
by: Doug Holland | last post by:
Currently I am responsible for writing the C# coding standards document for a client and I have been doing some investigations with ildasm to establish some additional best practices. When using either the C# equality operator '==' or the object.Equals() methods, which is better? Personally I prefer the object.Equals as it prevents accidental assignement using only a single equals, however the C# '==' is certainly less to write (not...
40
5689
by: Ike Naar | last post by:
In K&R "The C++ programming language (2nd ANSI C edition), the reference manual states (paragraphs 7.9 and 7.10) that pointer comparison is undefined for pointers that do not point to the same object. So if we have const char * foo = "foo" , * bar = "bar" ; int foobar = ( foo == bar ) ; would it mean that foobar is undefined?
4
1667
by: Matt Burland | last post by:
I'm a little confused about the way the default equality operator works with classes. Here's the situation, I have two comboboxes that are each filled with different object (i.e. ComboBox1 contains objects of class A, ComboBox2 contains objects of class B). What I'm trying to do is determine if a given object is contained in one of the comboboxes, i.e.: Combobox1.Items.Contains(MyA); Combobox2.Items.Contains(MyB); Now the problem is...
6
1825
by: benben | last post by:
I am a C++ guy recently migrated to C#. One of the thing I don't understand is assignment (=) and equality (==) operators. If I try to do the following: C a = new C; C b = a; Then I will get both a and b referring to the same object, which is not exactly the copy constructor semantics in C++. But I can do the following to remedy:
37
2790
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 behaviour, which is returning a value which is, really, id({}) < id(). He also said that default equality comparison will continue to be identity-based. This means that x == y will never raise an exception, as is the situation is now. Here's his reason:
7
1968
by: Gary Brown | last post by:
Hi, In C#, how do you determine two objects are the "same" rather than "equal?" In C/C++ you can check the addresses and LISP provides a rich set of equality operators but C# appears ambiguous. Search of the on-line documentation of "equal" and "same" yielded nothing useful. Thanks,
6
4489
by: Edward Diener | last post by:
Now that operator overloading allows to ref classes to be compared for equality using == syntax, how does one compare the actual ref pointers ( ^ ) for equality instead ? As an example: SomeRefObject ^ obj1(..initialized somehow); SomeRefObject ^ obj2(..initialized somehow); if (obj1 == obj2) // This compares the objects themselves for equality
3
1744
by: toton | last post by:
Hi, I have a struct Point { int x, int y; } The points are stored in a std::vector<Pointpoints; (global vector) I want to add equality (operator == ) for the point, which will check equality based on the position of the point in the vector rather than its x,y or any other criterion. Thus 2 free point (which are not in the vector are always unequal ) and so on. How to add this kind of equality operator ? Is comparing memory location like...
16
1657
by: DamienS | last post by:
In the interests of me saving hair, can someone please explain to me what's going on below? Why doesn't == work in comparing two int's when cast as objects? They're the same type. Note that it worked for strings. Thanks in advance, Damien
0
8483
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8824
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8673
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
7444
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
5703
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
4227
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...
0
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2818
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
1815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.