473,513 Members | 2,490 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 1541
On Sun, 4 May 2008 22:40:28 -0400, "barcaroller"
<ba*********@music.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.learn.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, "barcaroller"
<ba*********@music.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*******@rocketmail.com
Jun 27 '08 #3

"Jim Langston" <ta*******@rocketmail.comwrote in message
news:wM***************@newsfe05.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, "barcaroller" <barcarol...@music.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 objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 27 '08 #5
James Kanze <ja*********@gmail.comwrites:
On May 5, 4:40 am, "barcaroller" <barcarol...@music.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...@informatimago.com (Pascal J. Bourguignon)
wrote:
James Kanze <james.ka...@gmail.comwrites:
On May 5, 4:40 am, "barcaroller" <barcarol...@music.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 objektorientierter Datenverarbeitung
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...@gmail.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.fiwrites:
On 5 touko, 16:19, James Kanze <james.ka...@gmail.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.fisaid:
On 5 touko, 16:19, James Kanze <james.ka...@gmail.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
On 5 Maj, 16:48, Krice <pau...@mbnet.fiwrote:
On 5 touko, 16:19, James Kanze <james.ka...@gmail.comwrote:
First of all, you never compare with true or false.

I'm doing that. What could go wrong?
Probably nothing goes wrong although if (i == true) is to cryptic to
me when i is not boolean (in which case you should have written if (i
== 1). But the whole idea is one of obfuscation to me: if (i) serves
the purpose perfectly, and any extraneous comparison would get me
asking why, let me recheck the definition of i and (if I was a code
reviewer) return the code back to the OP.

/Peter
Jun 27 '08 #11
On 5 touko, 18:07, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.
I thought it was true.
Jun 27 '08 #12
On 2008-05-05 18:33:29 -0400, Krice <pa****@mbnet.fisaid:
On 5 touko, 18:07, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
>But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.

I thought it was true.
int i = get_some_value();
if (i)
do_something();

do_something will be called whenever get_some_value() returns any
non-zero value.

if ( i == true )
do_something();

do_something will be called whenever get_some_value() returns 1.

--
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 #13

"James Kanze" <ja*********@gmail.comwrote in message
news:89**********************************@e39g2000 hsf.googlegroups.com...
>
No. First of all, you never compare with true or false.
Why not? It's safer (and clearer) than using

if ( x )
if ( !foo() )
By using true/false, you are making it clear that you are dealing with a
boolean expression (as mostly intended) and not a variable/function that may
have any value.
Jun 27 '08 #14
Pascal J. Bourguignon wrote:
But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.
The language C++ guarantees that a value of type bool can only be one of
two things: true or false. Comparing a bool value with the literal true
is safe.
Jun 27 '08 #15
Pete Becker kirjoitti:
int i = get_some_value();
Why would anyone mix int with bool true or false?
Jun 27 '08 #16
barcaroller schrieb:
"James Kanze" <ja*********@gmail.comwrote in message
news:89**********************************@e39g2000 hsf.googlegroups.com...
>No. First of all, you never compare with true or false.

Why not? It's safer (and clearer) than using

if ( x )
if ( !foo() )
By using true/false, you are making it clear that you are dealing with a
boolean expression (as mostly intended) and not a variable/function that may
have any value.
Isn't it a better idea to make that clear with the name? After all, you
wouldn't use "x" and "foo" as identifiers in a real program :)

if ( is_safe )
if ( !fileExists() )
--
Christian Hackl
Jun 27 '08 #17
On May 5, 5:07 pm, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
Krice <pau...@mbnet.fiwrites:
On 5 touko, 16:19, James Kanze <james.ka...@gmail.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.
False is equal to false. It's never 0, or any other numeric
value. If you convert a bool to another numeric type, false
converts to 0, but that's a different problem. (Also, you
rarely would convert a bool to any other numeric type.))
But for true, it's something else. It may be 1, -1, 0xff, or
whatever not 0.
True is true. It's never 1, -1, 0xff or whatevert. It's not a
numeric value.

False and true are values of type bool. Type bool has exactly
two values, false, and true, and no others. A expression of
type bool cannot have a value 0, or 1, or -1 or 0xFF or
whatever. It can only have a value of false or true.

In C++, for historical reasons, bool converts to numeric types,
with false converting to 0, and true to 1. In C++, for
historical reasons, numeric types and pointers convert to bool,
with the result being the same as if you'd compared them to 0.
These conversions are really only present for historical
reasons, however, and you don't use them in well written code.
But in any case, it's harder to read boolean expression when
you add equivalences with the constants.
The real problem is that it is redundant. Suppose you write
something like:

if ( a == true )

Presumably, a has type bool, or the expression doesn't really
make sense. (If a has type int, then the expression "true", of
type bool, will be converted to the integral value 1. If this
is what is wanted, it's obfuscation.) But of course, the
expression "a == true" also has type bool. So by the same
logic, if we wanted to test whether it was true, we'd write:

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

Except, of course, that "(a == true) == true" has type bool, so
we'll write...

A condition requires a bool (or something which converts
implicitly to bool). If you've got a bool, you've already got
what you need. If you don't have a bool, the comparison
operators (==, !=, etc.) all result in a bool.

--
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
Jun 27 '08 #18
On May 6, 5:01 am, "barcaroller" <barcarol...@music.netwrote:
"James Kanze" <james.ka...@gmail.comwrote in message
news:89**********************************@e39g2000 hsf.googlegroups.com...
No. First of all, you never compare with true or false.
Why not? It's safer (and clearer) than using
if ( x )
if ( !foo() )
By using true/false, you are making it clear that you are
dealing with a boolean expression (as mostly intended) and not
a variable/function that may have any value.
How is it clearer? If the expression doesn't have type bool,
you shouldn't compare with true or false, but rather with
something of the correct type. If the expression has type bool,
there's no point in comparing, since the whole point of the
comparison is to get a type bool. And if you compare a boolean
expression with true or false, you'll never finish, because a
comparison is a boolean expression.

--
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
Jun 27 '08 #19
On 2008-05-05 23:01:32 -0400, "barcaroller" <ba*********@music.netsaid:
>
"James Kanze" <ja*********@gmail.comwrote in message
news:89**********************************@e39g2000 hsf.googlegroups.com...
>>
No. First of all, you never compare with true or false.

Why not? It's safer (and clearer) than using

if ( x )
if ( !foo() )
By using true/false, you are making it clear that you are dealing with a
boolean expression (as mostly intended) and not a variable/function that may
have any value.
That's what the declarations of x and foo() do. Adding redundant
information makes code harder to maintain, not "safer" (whatever that
means).

--
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 #20
On 2008-05-06 02:58:01 -0400, Krice <pa****@mbnet.fisaid:
Pete Becker kirjoitti:
>int i = get_some_value();

Why would anyone mix int with bool true or false?
Often a function returns a value that indicates whether it succeeded,
and if not, an error code that indicates what the failure was.
Sometimes all you care about is whether it succeeded. There's a long
tradition in C and C++ of using this kind of bool-and-a-half value.

--
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 #21
On 2008-05-06 02:02:24 -0400, Eberhard Schefold <eb**@gmx.desaid:
Pascal J. Bourguignon wrote:
>But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.

The language C++ guarantees that a value of type bool can only be one
of two things: true or false. Comparing a bool value with the literal
true is safe.
But comparing the return value of a function that returns an int
against true won't necessarily give you a correct result.

--
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 #22
On May 6, 12:52 pm, Pete Becker <p...@versatilecoding.comwrote:
On 2008-05-06 02:58:01 -0400, Krice <pau...@mbnet.fisaid:
Pete Becker kirjoitti:
int i = get_some_value();
Why would anyone mix int with bool true or false?
Often a function returns a value that indicates whether it
succeeded, and if not, an error code that indicates what the
failure was. Sometimes all you care about is whether it
succeeded. There's a long tradition in C and C++ of using this
kind of bool-and-a-half value.
But you wouldn't mix the int with true or false.

At least in the C/C++ communities I've been active in, the
largest single tradition involved defining sentinal values to be
used for an error: typically, a function which can only return
positive values will be declared to return an int, with -1 for
error. Which, of course, doesn't lend itself to an implicit
conversion, much less with comparison with true or false.

More recently, of course, Posix has adopted the tradition of
returning 0 for success, and a strictly positive error code for
error, so you could write:

if ( pthread_create( ... ) ) {
// Didn't work...
}

Which, of course, is exactly the opposite convention that one
finds in:

if ( std::getline( input, line ) ) {
// Worked...
}

Here too, however, you wouldn't mix with true or false; you
wouldn't write:

if ( pthread_create( ... ) == false ) {
// Worked...
}

(and of course:

if ( pthread_create( ... ) == true ) {
// Didn't work...
}

doesn't work at all.)

Globally, I find the convention of "true" for success slightly
more intuitive, but it doesn't leave any possibility for
additional error codes. I'll use the direct test on the
operation with iostream, because it is *the* standard C++ idiom,
but in all other cases, I'll use comparison.

At least where "simple" types are concerned. In more complex
cases, I've found it useful to return a class with the error
status and additional information. And to have the class
convert implicitly to bool. But here again: I only use the
conversion (the bool) for a direct check, where I don't need any
of the additional information---I don't compare the results with
true or false.

--
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
Jun 27 '08 #23
James Kanze schrieb:
if ( (a == true) == true )

Except, of course, that "(a == true) == true" has type bool, so
we'll write...
The motivation for precisely one comparison with true seems rather
obvious to me -- human language. We say

If that expression is true, then ...

not

If that expression, then ...

nor

If that expression is true, is true, then ...

I'm not advocating to compare a bool value with true in an if clause,
but if somebody prefers that style, I don't see the need to talk them
out of it.
Jun 27 '08 #24
Eberhard Schefold <eb***************@de.bosch.comwrites:
James Kanze schrieb:
> if ( (a == true) == true )
Except, of course, that "(a == true) == true" has type bool, so
we'll write...

The motivation for precisely one comparison with true seems rather
obvious to me -- human language. We say

If that expression is true, then ...

not

If that expression, then ...

nor

If that expression is true, is true, then ...
You have a strange human language. In the human languages I speak,
we usually say "If it is raining then we won't go outside." or "If it
is sunny then let's eat ice cream.".

We don't usually say "If it is true that it is sunny, then let's eat
ice cream.". Saying such a locution would indicate that you don't
know yourself whether it's sunny or not, that you have been told so,
and that you don't believe it.

I'm not advocating to compare a bool value with true in an if clause,
but if somebody prefers that style, I don't see the need to talk them
out of it.
Well of course, it's a question of style. If we had more powerful
editors(1), they could correct these stylistic variants as well as they
correct the indentation.

(1) actually, we have powerful enough an editor: emacs, the question
is whether we have enough time to customize it to do this kind of
things ;-)

--
__Pascal Bourguignon__
Jun 27 '08 #25
On Tue, 06 May 2008 16:04:19 +0200, Eberhard Schefold wrote:
James Kanze schrieb:
> if ( (a == true) == true )

Except, of course, that "(a == true) == true" has type bool, so we'll
write...

The motivation for precisely one comparison with true seems rather
obvious to me -- human language. We say

If that expression is true, then ...
We we don't (at least I don't) say "If n is equal to 1 is equal to true,
then ..."
not

If that expression, then ...
I do say: "If n is equal to 1, then ..."

[...]
I'm not advocating to compare a bool value with true in an if clause,
but if somebody prefers that style, I don't see the need to talk them
out of it.
I might see the need to talk them into using more sensible variable
names: e.g.

if (need_user_input) ...

doesn't need an " == true" to make it human language-friendly.

--
Lionel B
Jun 27 '08 #26
Pascal J. Bourguignon wrote:
You have a strange human language. In the human languages I speak,
we usually say "If it is raining then we won't go outside." or "If it
is sunny then let's eat ice cream.".
if( a() == true )

rather reminds me of a human language sentence than

if( a() )

does. Yes, I perceive it that way -- no apologies.

I prefer the latter form in programming, but I can understand why some
people prefer the first.
Jun 27 '08 #27
Lionel B wrote:
I might see the need to talk them into using more sensible variable
names: e.g.

if (need_user_input) ...

doesn't need an " == true" to make it human language-friendly.
Good point.
Jun 27 '08 #28
Stefan Ram wrote:
That's why a sentence is a better name for a predicate than »a«.

if( server_is_up() )...

Now, this is more natural-language like than

if( server_is_up() == true )...
Generally I certainly agree with Lionel and you. But it's not always
that easy. Sometimes you don't have control over the naming, and even if
you have, often the return value only indicates success or failure of a
larger procedure with lots of side effects, say,

if( GenerateRevenueReports() )
...

I wouldn't want to change that name into something more "boolean", say,

if( GenerateRevenueReportsWasSuccessful() )
...

It's not clear now if the function actually performs the action or only
queries for its status. So, even with all the arguments, I still
understand why some people might find

if( GenerateRevenueReports() == true )
...

clearer to understand.
Jun 27 '08 #29
On 6 May, 16:13, Eberhard Schefold <eberhard.schef...@de.bosch.com>
wrote:
Stefan Ram wrote:
* That's why a sentence is a better name for a predicate than »a«.
if( server_is_up() )...
* Now, this is more natural-language like than
if( server_is_up() == true )...

Generally I certainly agree with Lionel and you. But it's not always
that easy. Sometimes you don't have control over the naming, and even ifyou have, often the return value only indicates success or failure of a larger procedure with lots of side effects, say,
well in that case the function is badly named and has
an odd return type

* * if( GenerateRevenueReports() )
* * * *...

I wouldn't want to change that name into something more "boolean", say,

* * if( GenerateRevenueReportsWasSuccessful() )
* * * *...

It's not clear now if the function actually performs the action or only
queries for its status. So, even with all the arguments, I still
understand why some people might find

* * if( GenerateRevenueReports() == true )
* * * *...

clearer to understand.
I'd be tempted to hide the truth :-)

const bool success = true;

if (GenerateRevenueReports() == success)

I've done this with APIs that use boolean parameters.

const bool erase_background = true;

InvalidateRect (hwnd, 0, erase_background);


--
Nick Keighley
Jun 27 '08 #30
On 2008-05-06 12:53, Pete Becker wrote:
On 2008-05-06 02:02:24 -0400, Eberhard Schefold <eb**@gmx.desaid:
>Pascal J. Bourguignon wrote:
>>But for true, it's something else. It may be 1, -1, 0xff, or whatever
not 0.

The language C++ guarantees that a value of type bool can only be one
of two things: true or false. Comparing a bool value with the literal
true is safe.

But comparing the return value of a function that returns an int
against true won't necessarily give you a correct result.
But then again, sloppy programming has never been a good way to get
correct code. If a function returns something else than a bool you
should compare it to the expected result and not rely on the implicit
conversion (which should never have been allowed into the language).

--
Erik Wikström
Jun 27 '08 #31

"Erik Wikström" <Er***********@telia.comwrote in message
news:fo*****************@newsb.telia.net...
On 2008-05-06 12:53, Pete Becker wrote:
>On 2008-05-06 02:02:24 -0400, Eberhard Schefold <eb**@gmx.desaid:
>>Pascal J. Bourguignon wrote:

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

The language C++ guarantees that a value of type bool can only be one
of two things: true or false. Comparing a bool value with the literal
true is safe.

But comparing the return value of a function that returns an int
against true won't necessarily give you a correct result.

But then again, sloppy programming has never been a good way to get
correct code. If a function returns something else than a bool you
should compare it to the expected result and not rely on the implicit
conversion (which should never have been allowed into the language).
The reason for much of the strangeness of fundamental types semantics in C++
is inherited AFAICS from BCPL, one of the main precursors to C.
BCPL didnt differentiate ints and pointers. I think that "heritage" can be
traced back nearly 40 years ago now!

There was I believe a fair amount of argument about changing the semantics
when C was standardised, but not much could be done for the standard "legacy
code" reasons.

regards
Andy Little

regards
Andy Little
Jun 27 '08 #32
On 2008-05-06 12:08:43 -0400, Erik Wikström <Er***********@telia.comsaid:
On 2008-05-06 12:53, Pete Becker wrote:
>On 2008-05-06 02:02:24 -0400, Eberhard Schefold <eb**@gmx.desaid:
>>Pascal J. Bourguignon wrote:

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

The language C++ guarantees that a value of type bool can only be one
of two things: true or false. Comparing a bool value with the literal
true is safe.

But comparing the return value of a function that returns an int
against true won't necessarily give you a correct result.

But then again, sloppy programming has never been a good way to get
correct code. If a function returns something else than a bool you
should compare it to the expected result and not rely on the implicit
conversion (which should never have been allowed into the language).
I'm not sure whether you think you're disagreeing with what I said, so
let me say it again: a function that returns a non-zero value to
indicate success doesn't necessarily return 1.

--
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 #33
Pete Becker wrote:
I'm not sure whether you think you're disagreeing with what I said, so
let me say it again: a function that returns a non-zero value to
indicate success doesn't necessarily return 1.
But why would anyone compare a non-bool return value with a bool
literal? Do you think this is a common idiom -- or a frequent mistake?
Jun 27 '08 #34
Eberhard Schefold wrote:
Pete Becker wrote:
>I'm not sure whether you think you're disagreeing with what I
said, so let me say it again: a function that returns a non-zero
value to indicate success doesn't necessarily return 1.

But why would anyone compare a non-bool return value with a bool
literal? Do you think this is a common idiom -- or a frequent
mistake?
Why would anyone compare a bool return value with a bool literal? :-)
Bo Persson
Jun 27 '08 #35
On 2008-05-06 19:39, Pete Becker wrote:
On 2008-05-06 12:08:43 -0400, Erik Wikström <Er***********@telia.comsaid:
>On 2008-05-06 12:53, Pete Becker wrote:
>>On 2008-05-06 02:02:24 -0400, Eberhard Schefold <eb**@gmx.desaid:

Pascal J. Bourguignon wrote:

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

The language C++ guarantees that a value of type bool can only be one
of two things: true or false. Comparing a bool value with the literal
true is safe.

But comparing the return value of a function that returns an int
against true won't necessarily give you a correct result.

But then again, sloppy programming has never been a good way to get
correct code. If a function returns something else than a bool you
should compare it to the expected result and not rely on the implicit
conversion (which should never have been allowed into the language).

I'm not sure whether you think you're disagreeing with what I said, so
let me say it again: a function that returns a non-zero value to
indicate success doesn't necessarily return 1.
I'm arguing against relying on explicit conversion to bool, if the
function returns non-zero on success you compare against non-zero:

if (0 != foo())

--
Erik Wikström
Jun 27 '08 #36
On 6 touko, 17:31, Lionel B <m...@privacy.netwrote:
if (need_user_input) ...
doesn't need an " == true" to make it human language-friendly.
I'm using ==true always. I never got used in "if (x)" style, it's
confusing. But you earthlings don't always act in logical way.
Jun 27 '08 #37
On 2008-05-06 13:46:31 -0400, Eberhard Schefold
<eb***************@de.bosch.comsaid:
Pete Becker wrote:
>I'm not sure whether you think you're disagreeing with what I said, so
let me say it again: a function that returns a non-zero value to
indicate success doesn't necessarily return 1.

But why would anyone compare a non-bool return value with a bool
literal? Do you think this is a common idiom -- or a frequent mistake?
It's a frequent mistake, as illustrated in the deep context that has,
unfortunately (and perhaps unavoidably), disappeared.

--
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 #38
On May 6, 5:13 pm, Eberhard Schefold <eberhard.schef...@de.bosch.com>
wrote:
Stefan Ram wrote:
That's why a sentence is a better name for a predicate than »a«.
if( server_is_up() )...
Now, this is more natural-language like than
if( server_is_up() == true )...
Generally I certainly agree with Lionel and you. But it's not
always that easy. Sometimes you don't have control over the
naming, and even if you have, often the return value only
indicates success or failure of a larger procedure with lots
of side effects, say,
if( GenerateRevenueReports() )
...
I wouldn't want to change that name into something more "boolean", say,
if( GenerateRevenueReportsWasSuccessful() )
...
It's not clear now if the function actually performs the
action or only queries for its status. So, even with all the
arguments, I still understand why some people might find
if( GenerateRevenueReports() == true )
...
clearer to understand.
It doesn't say anything more than just:
if ( GenerateRevenueReports() ) ...

I think it was Herb Sutter who first brought up the issue, but
there's already a serious problem if a function named
GenerateRevenueReports() returns a bool to indicate success: is
it true, the function succeeded, or true, there was an error?
The correct way to handle this is with an enum:

enum Result { success, failure } ;
Result GenerateRevenueReports() ;

In which case, of course, you write:

if ( GenerateRevenueReports() == success )
...

My general rule is that function names are verbs or verbal
clauses, and that predicate functions always use a form of the
verb to be or to have, e.g.: isRunning(), hasNoProblems(). Any
other function will use an enum (or some other user defined
type---I rather like a user defined type which asserts in its
destructor if it hasn't been tested) to report success or
failure.

There are exceptions, of course. The iostream idiom is too
ubiquious to be ignored, for example (and you can't change the
standard library even where it is completely irrational). And
there are cases where it makes sense to treat an extended type
as a bool, or verbs other than to be or to have which logically
respond with a bool (e.g. RegularExpression::matches()).

--
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
Jun 27 '08 #39
On Tue, 06 May 2008 11:50:27 -0700, Krice wrote:
On 6 touko, 17:31, Lionel B <m...@privacy.netwrote:
> if (need_user_input) ...
doesn't need an " == true" to make it human language-friendly.

I'm using ==true always. I never got used in "if (x)" style, it's
confusing. But you earthlings don't always act in logical way.
Ah, maybe your Martian grammar uses ternary logic as standard:

if (need_user_input == true)
\\ do something
else if (need_user_input == false)
\\ do something else
else if (need_user_input == um____not_sure_really)
\\ drink coffee

--
Lionel B
Jun 27 '08 #40
In article <re*****************@ram.dialup.fu-berlin.de>, ra*@zedat.fu-
berlin.de says...

[ ... ]
In a Java program (off topic here, but just to show how sane
C++ is in comparison), I once came across:

if (a[i] != a[i])

It took me several seconds to remember how this might be true
in Java (Hint: it has nothing to do with the array access, the
same effect can be seen with »if( a != a )«.)

If the reader knows Java, but also does not understand this
expression immediately, this would prove that it is hard to read.

(Another hint: The type of the operands of »!=« is »double«.)
Actually, the same can occur in C++. TR1 provides a more direct method
though: if (isnan(a[i]). Unless something changes, C++ 0x will have this
as well.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #41
On May 7, 5:16 pm, r...@zedat.fu-berlin.de (Stefan Ram) wrote:
James Kanze <james.ka...@gmail.comwrites:
My general rule is that function names are verbs or verbal
»Procedure names should reflect what they do;
function names should reflect what they return.«
Notes on Programming in C; Rob Pike; February 21, 1989
http://www.lysator.liu.se/c/pikestyle.html
This is the same article that says "include files should never
include include files", right?
This reflects the natural-language distinction between verbal
phrases and noun phrases. For example, the name »sin« of the
header »cmath« perfectly reflects what it returns. »sin( 0.0 )«
coresponds to the natural-language noun phrase »the sine of zero«.
I can not imagine how replacing »sin« it by a verb or
verbal phrase would improve things.
The only problem are mixed operations (functions) that both do
something and return a result.
if( fopen( "alpha", "r" ))...
Such beasts do not occur in natural-language use. So no
model for them can be derived from natural-language use.
A possible solution using an abstract-datatyp object
would be to separate the two. For example as follows:
File f;
f.open( "alpha", "r" );
if( f.is_ready_for_use() )...
Seriously, you have a point, and the issue with regards to
functions is a little more complex:

First, if the "function" does something, it's not a function;
it's a procedure with an out parameter. The name should be a
verb or a verbal phrase.

Second, math functions are a special case: sin isn't a normal
English word, and it means exactly that: the function in
question. Any other name (e.g. std::sin, or Math.sin) just
doesn't cut it.

For the rest, I tend to distinguish: if the function returns a
pure value, or a reference to some object which is conceptually
part of the object it is called on, I use the name of the value
or the object---generally a noun. If the returned value is an
object, but is not conceptually part of the object it is called
on, then I use a verb phrase: "Whatever::widget()" returns a
reference to the widget which is conceptually part of Whatever,
but "Whatever::getWidget()" or "Whatever::findWidget()" will
return a widget, or a reference to a widget, that may exist
elsewhere, which presumably, Whatever has to do some work to
find, and "Whatever::createWidget()" returns some new object
(usually with transfer of ownership).

--
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
Jun 27 '08 #42

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

Similar topics

1
1553
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...
40
5653
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...
4
1660
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...
6
1819
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...
37
2762
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...
7
1962
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....
6
4481
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: ...
3
1736
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...
16
1640
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...
0
7260
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,...
0
7160
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...
1
7099
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
7525
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...
0
5685
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,...
1
5086
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
4746
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...
0
3222
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1594
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 ...

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.