Velocity Reviews > if (f() != FAIL) or if (FAIL != f())?

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

Wenjie
Guest
Posts: n/a

 07-28-2003
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

Richard Bos
Guest
Posts: n/a

 07-28-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) (Wenjie) wrote:

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

Ashish
Guest
Posts: n/a

 07-31-2003

"Wenjie" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) m...
> 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

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.

--
-Ashish
--------------------------------------------------------------------------
Hi! I'm a shareware signature! Send \$5 if you use me, send \$10 for manual!
http://www.123ashish.com http://www.softwarefreaks.com

E. Robert Tisdale
Guest
Posts: n/a

 07-31-2003
Wenjie wrote:

>
>
>
> 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.