Alex Rivera | Logout

Do you prefer "if (var)" or "if (var != 0)"?

Asked 2009-01-01T10:42:15.523
22

I've been programming in C-derived languages for a couple of decades now. Somewhere along the line, I decided that I no longer wanted to write:

if (var)    // in C
if ($var)   # in Perl

when what I meant was:

if (var != 0)
if (defined $var and $var ne '')

I think part of it is that I have a strongly-typed brain and in my mind, "if" requires a boolean expression.

Or maybe it's because I use Perl so much and truth and falsehood in Perl is such a mine-field.

Or maybe it's just because these days, I'm mainly a Java programmer.

What are your preferences and why?

Edit
Report

3 Answers

18
if (var)

Less to type, as long as you're sure you're not testing the wrong thing.

answered 2009-01-01T10:46:17.153
3

If you have a value that is intended to be a boolean, you should feel comfortable just doing:

if ( var )
if ( $var )

If you have more specific requirements for your "boolean," you can always do some prep work/tests on your variable and assign it to another variable with better defined boolean values.

$shouldDoSomething = ( defined $var and $var ne '' ) ? 1 : 0;

if ( $shouldDoSomething ) {
    // Handle this case.
}

This can clean up the code quite a bit. It also helps if you intend to use this condition more than once. I find this happens pretty frequently, actually. Also, I feel like the above is far more readable than doing it inline:

if ( defined $var and $var ne '' ) {
    // Handle this case.
}
answered 2009-01-01T10:53:50.430
0

There are languages in which you have no choice. In Specman, for instance, you can't write:

var x: uint;

if (x) {
    bla
};

But you can do:

var x: uint;

if (x != 0) {
    bla
};

or

var x: bool;

if (x) {
    bla
};

However, you can't do:

var x: bool;

if (x != 0) {
    bla
};

Because you can't compare a boolean to an integer.

Coming from C and Perl I always thought this to be annoying, until I actually started writing a lot in Specman. The code is simply clearer like this.

answered 2009-12-29T08:06:44.937

Your Answer