Checking for True

  • Thread starter Thread starter Burrows
  • Start date Start date
B

Burrows

A new college at work use the following

if(true==x)
{
.........
}

now I have through all my programming years and through various
languages have always used

if(x==true)
{
.........
}

Now yes we get the same result in checking for a true value but he's a
smug sod so don't wish to question his methods. So should I tell him
to change to my method or adopt his as it's better????
 
A new college at work use the following

if(true==x)
{
........
}

now I have through all my programming years and through various
languages have always used

if(x==true)
{
........
}

Now yes we get the same result in checking for a true value but he's a
smug sod so don't wish to question his methods. So should I tell him
to change to my method or adopt his as it's better????

I personally find that putting the constant first is horrifically ugly, but
ultimately it's the same either way to the compiler. I think it's harder to
read, like talking in reverse (much the same reason I despise top posting,
but that's a flamewar for another day).

I like my conditionals to read "If <the thing I'm interested in> <compares
to> <a certain value>"; it just flows better.
 
I forgot to comment on the obvious: explcitly comparing to true is the REAL
ugliness here. Just do

if (x)
{
...
}

But I think everyone gets the gist of what you're saying.
 
A new college at work use the following

if(true==x)
{
........
}

now I have through all my programming years and through various
languages have always used

if(x==true)
{
........
}

Now yes we get the same result in checking for a true value but he's a
smug sod so don't wish to question his methods. So should I tell him
to change to my method or adopt his as it's better????

You should use:

if(x)
{
...
}

The reason behind the if(constant==variable) instead of the
more natural if(variable==constant) is to prevent writing
if(variable=constant) by accident.

Not a particular good reason in my opinion, but there are
some people with a C/C++ background that use it.

Arne
 
Note that doing so is not really an issue in C#, because types are not
generally implicitly convertible to Boolean, and so an unintended
assignment in an "if" statement will cause a compile-time error.

The one obvious exception is of course some along the lines of "if (x =
true)", but as stated by both Jeff and Arne, that's a silly thing to
write in any case, whether you want = or ==.
<snip>

The other exception is if (x = y)
rather than just comparing to a constant, where x and y are both
Boolean. I got caught by this typo myself once where I really
wanted
if (x == y)

Oz
 
Back
Top