if (f() != FAIL) or if (FAIL != f())?

W

Wenjie

Hello,


I have a question concerning style related to conditional
decision:

#define FAIL -1
int f();

if (f() != FAIL) or better if ( FAIL != f())? Why?


Thank you!
Wenjie
 
R

Richard Bos

#define FAIL -1
int f();

if (f() != FAIL) or better if ( FAIL != f())? Why?

The former, since it is the clearer by far.

There are people who advocate using the second, because it can prevent
an error caused by carelessness in completely different circumstances
which cannot possibly occur here. Ignore them; writing unclear code
usually produces more bugs than silly tricks like that solve.

Richard
 
A

Ashish

Wenjie said:
Hello,


I have a question concerning style related to conditional
decision:

#define FAIL -1
int f();

if (f() != FAIL) or better if ( FAIL != f())? Why?
The second style is used to avoid the common mistake of assigning to a
variable instead of comparing.

For example...
if(a == 5) could be wrongly written as if(a = 5), which would return true,
but instead of comparing a with 5, it would assign the value of 5 to a.

But, if you use the second style, using an if(5 = a) would give you an
error.

In your case, it doesnt matter.
 
E

E. Robert Tisdale

Wenjie said:
I have a question concerning style related to conditional
decision:

#define FAIL -1
int f(void);

if (f() != FAIL)

or better

if ( FAIL != f())

int i = f();
if (FAIL == i)

is better than

int i = f();
if (i == FAIL)

because a typical typographical error

if (i = FAIL)

will assign i the value of FAIL
and the conditional will evaluate to true
even if 0 == f().

Both of example should cause a diagnostic message
to be logged by the compiler if you replace == with =
because both f() and FAIL are right-hand sides.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,614
Members
45,293
Latest member
Hue Tran

Latest Threads

Top