comparison

R

Richard Heathfield

Ajay said:
What is the difference betweem

if (x == 1)

AND

if (1==x)

The reason some people (including myself) prefer the second is that the
error of mistyping = instead of == will be picked up by the compiler.
Consider:

if(x = 1)

and

if(1 = x)

The former is legal C, but not what you wanted (or you would not have
bothered with the if). The second is not legal C, so the compiler will
diagnose it.
 
C

Chris Dollin

Ajay said:
What is the difference betweem

if (x == 1)

AND

if (1==x)

The operands to `==` are in opposite orders.

Some people feel that the second form gives some immunity to
the `x = 1` problem.

Other people feel that the second order is sufficiently unnatural
that it will /cause/ problems.

It's likely that the best tactic is to pick one of the forms,
and use that consistently though your workgroup or compatibly
with your audience.

You are invited to guess my opinion from the subtle hints in
this post.
 
R

Richard Bos

Ajay said:
What is the difference betweem

if (x == 1)

AND

if (1==x)

The latter will cause you to think that you'll be automatically warned
if you accidentally type = instead of ==, which means that you'll have a
much harder time finding the bug when you inevitably write if (y=x).

Richard
 
M

Martin Ambuhl

Ajay said:
What is the difference betweem

if (x == 1)

AND

if (1==x)

Apart from typography, none.
Since my compiler will warn me about
if (x = 1)
and my normal natural language way of expressing the comparison is
if x is equal to 1
I prefer the first.

People who have turned off their diagnostics (a bad thing), or use a
less helpful compiler, or who think of 1 as a variable, as in
if 1 is equal to x,
will prefer the second.
 
R

Richard Heathfield

Richard Bos said:
The latter will cause you to think that you'll be automatically warned
if you accidentally type = instead of ==,

Wrong. It will cause you to *know* that you'll be automatically warned if
you accidentally type = instead of == when comparing a constant and an
lvalue.
which means that you'll have a
much harder time finding the bug when you inevitably write if (y=x).

No. I agree that such a bug is *hard* to find if your compiler doesn't
notice it, but just because a related error is *easier* to find, that does
not make /this/ error *harder* to find than it was before.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top