Idiomatic way to check for non-zero - c

When I wish to check if a value is 0 in C, how is it idiomatically done?
if (!num)
if (num == 0)

While this is a matter of taste, I find it pretty much depends on intention. If the value is to be used as a boolean, ! is alright. If the value is counting something the equality makes more sense.
if (!isVisible) {...}
if (isVisible == 0) {...} // Intention not as clear as line above.
if (numberOfItems == 0) {...}
if (!numberOfItems) {...} // Intention not as clear as line above.

I always prefer the second way:
if (num == 0)
As num == 0 or ptr == NULL evaluates to a boolean which is the intent. The Java compiler enforces this form, but C/C++ compilers don't.
The worst example of this would be:
if (!strcmp(str, "something"))
Which really disguises its intent as the strcmp family of functions don't return boolean, they return positive, zero, or negative (as pointed out by #JoachimPileborg).
However if the int is being used to represent a boolean type, which C does not have a builtin type for, then this form is OK:
if (!b)
But this can be made self documenting by creating a custom type:
typedef int bool;
#define true 1
#define false 0
bool b = true;
if (!b)
{
... etc
}

Whatever the others told you WITH AN EXCEPTION!
Don't do it with float and double. IEEE 754 floats/doubles/long doubles (the most commonly used) often don't contain exact values, so comparing them directly with 0 is foolish (or doing if (!floatValue))
Example: http://ideone.com/PIUflA
float f = 0.3;
f -= 0.2;
f -= 0.1;
if (!f)
{
printf("zero\n");
}
else
{
printf("non zero\n");
}
if (f == 0)
{
printf("zero\n");
}
else
{
printf("non zero\n");
}
With unoptimized compilation can return (on ideone does)
non zero
non zero
(if you enable optimizations, the compiler could pre-compute some values in higher precision and round them to 0)

I think it depends on the context. If the variable refers to a boolean value is better first choice. Otherwise, the second is better.

It's done however you want it to be done, in terms of your style. I don't see it as mattering as long as your consistent and it's clear on what you're trying to do, or if you do it in cases where it may flow better in an English sentence and may put emphasis on what your doing.
For sake of clarity I usually have if (num == 0), since it takes less thinking to understand what I'm doing when I'm going over my code.

!!value will work too if you want to check if value is non-zero.
!value evaluates to 1 when value=0 and 0 when value≠0.
The second ! flips it, making !!value evaluate to 1 when value≠0 and 0 when value=0.

We may argue which way is better, but idiomatic, though for what I can tell by other answers archaic, would be if(!num).

For the compiler, it does not matter, of course. For the human reader it does. Since both forms are used by other human beings, you should get used to them and recognise them. Personally, I prefer the shortest form, which takes less time (less tokens, especially parenthesis) to read and understand. Especially:
if (!ptr) {}
if (!strcmp(a,b)) {}
are easyer to read than
if (ptr != NULL) {}
if (strcmp(a,b) == 0) {}
if (0 == strcmp()) {}
The last form makes me physically sick.

Related

Which one is safer to use? " ==TRUE" or " != FALSE"

Is it better to compare a boolean type variable with:
== FALSE and != FALSE; or
== TRUE and != TRUE?
Is it better to compare a boolean type variable with " == FALSE" and " != FALSE" or with " ==FALSE" and " ==TRUE" ?
Neither.
With the C boolean type _Bool, do not use == or != to assess truth-ness against a constant.
#Steve Summit #Antti Haapala #John Bode
_Bool x;
if (x) // to assess truth-ness
if (!x) // to assess false-ness
If a strong desire remains to use ==, !=, like many style issues, best to follow your group's coding guidelines.
Lacking group's coding guidelines - make them.
Use <stdbool.h> as able to access bool, true, false rather than code TRUE, FALSE.
#Eugene Sh.
Which one is safer to use? “ ==TRUE” or “ != FALSE”
Note that comparing a == TRUE can fail unexpectedly as the operands are compared as integers, FP or pointers, not as boolean. This may fail to compare truth-ness should a be a non-boolean with a "truth" value other than 1 even if TRUE is a boolean 1.
double a = 0.999999;
// Both are false
if (a == TRUE) { ... } // The arithmetic value of `a` is used, not its "truth"
if (a == FALSE) { ... }
// better as
if (a) { ... } // As if `a != 0`
else { ... }
Consider cases where the "truth" is returned as non-zero, perhaps not 1.
if(islower('a') == TRUTH) ... // The if() block might or might not execute
if(islower('a')) ... // The if() block will execute
a != 0 or a != false tends to be safer.
Style: I find == code easier to follow than != as negations add mental complexity for people. Example
TRUE and FALSE is not standard C and should therefore not be used, unless perhaps you are coding against an old C90 library that uses them (such as Windows API).
The boolean type in C is _Bool. It can be used as bool and should be set to values true or false from stdbool.h
The need to explicitly compare a boolean against true/false suggests poor variable naming. A somewhat common naming standard for booleans is to prefix them with is, such as: while(!isReady) { ... }.
The ==and != operators are equally safe. Both could in theory be mixed up with = and =!, but any decent compiler will warn for that ("assignment in expression"/"possible incorrect assignment").
Everey syntax has its own meaning and there is not better or safer way. But you should always consider these special points in comparison to decide which syntax is safer in your case:
in C language NUMBERS represent booleans: 0 is FALSE and other numbers are TRUE. You may restrict to stdbool.h to prevent mixing up integers and boolean.
if you connect to SQL databse uisng C , in SQL, a comparison against NULL is not true nor false.
If are working in team I suggest to all team members to use if (something==TRUE) rather than if(something) because indicates that you mean boolean from something not an Integer. Meke sure that your temameates agree with this syntax and also make sure that you have considered case number 1!

Should you use '>=' instead of '==' to be extra safe when coding with other types than float?

When working with floating-points one should use
a <= 0.0
instead of
a == 0.0
to make sure that you get the desired behaviour, as there is the problem with round-off errors when using floating-point variables.
But when using other variable types like int could it be useful to do the same? Like you have a for loop iterating over an int variable (like an index) and when it gets to a number it should do something. Should you then set the comparison to be >= instead of == when it should result in the same output? Like could there ever be a case where the == is not evaluated in the following case:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
And that it would be "safer" to do the following instead:
for (int i = 0; i < 10; i++)
{
if (i >= 5)
{
break;
}
}
If there is no difference between the two when it comes to coding "safe" is there any performance or readability difference or other thing that can make one choose between the ways to code?
Tried to google this but couldn't find anything stating either way. But that might have to do with the problem with searching for operators.
Am I too paranoid for asking this?
The premise of the question is wrong; blindly using a <= 0.0 instead of a == 0.0 is not a valid practice with floating point. See How dangerous is it to compare floating point values? for a treatment of the topic.
With that said, there are some cases where use of inequality relational operators are "more hardened" than use of the equality operator, and vice versa. In general, I would recommend against it since it's likely to give you a false sense of safety; for example, in the example in your question with i==5 vs i>=5, the compiler is likely to be able to prove they're the same, and optimize either to the other if needed. This means it will not necessarily do anything to protect you against stack overflows or neutrinos or any other cause by which the value of i might become something other than 0..5 outside of the defined semantics of the language.
There are also some cases where use of equality is defined by inequality is not, particularly involving pointers. If pos and end are both pointers, pos==end is well-defined as long as they are both valid. But if they are both null, while pos==end is well-defined and true, pos>=end is undefined behavior. Likewise if they both point into different arrays (in particular if end points to a sentinel not part of your array), pos==end will always be false, but pos>=end is undefined behavior.
I also find it misleading to write if (i>=5) when you know i>5 is logically impossible - it makes the reader stop to think about whether it's possible, and if not, why you wrote it that way instead of if (i==5).
The answer is, it depends. If you have a loop like this:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
Then there is no danger in i skipping 5.
On the other hand, if you have something like this:
volatile int i;
void interrupt(void)
{
i++;
}
void foo(void)
{
for (i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
}
Then i may change outside the normal flow of the program (e.g. because of an interrupt). In this case >= would be prudent.
Like could there ever be a case where the == is not evaluated
No, using == is safe. Integers represent all values within the range of the integer type used accurately. There are no surprises.
Should you then set the comparison to be >= instead of ==
As the result is the same, you can do both but I would find >= confusing. So for readability I prefer ==
is there any performance . . . that can make one choose between the ways to code
You can't tell by looking at the C code. It depends on the system (CPU) used. In general I would however doubt that you would experience any major difference.

Is it safe to compare floats strictly, given we do no operations on them?

Normally, when we want to test fractional numbers for equality, we do so with some amount of uncertainty, because of approximate nature of IEEE754.
if (fabs(one_float - other_float) < SUFFICIENTLY_SMALL) {
consider them equal;
}
Other approach might be to cast the floats to integers of specific magnitude, and compare resulting integers instead.
if ((uint)one_float == (uint)other_float) {
consider them equal;
}
But consider the situation where our floats never undergo any arithmetics, and the only thing we do with them is assignment.
// Might be called at any moment
void resize(float new_width, float new_height)
{
if (current_width == new_width && current_height == new_height) {
return;
}
accomodate framebuffers;
update uniforms;
do stuff;
current_width = new_width;
current_height = new_height;
}
In the example above, we have an event handler that may fire up spontaneously, and we want to reallocate resources only if real resize occurred. We might take the usual path with approximate comparison, but that seems like a waste, because that handler will fire up pretty often. As far as I know, floats are assigned just as everything else, using memory move; and equality operator performs just the memory comparison. So it looks like we are in a safe harbour. When checked on x86 and ARM, this assumption holds, but I just wanted to be sure. Maybe it's backed by some specs?
So, is there something that might change floats when only assigning them? Is the described approach viable?
A mass of "should"s follows.
I don't think there's anything that says an assignment from float to float (current_width = new_width) couldn't alter the value, but I would be surprised if such a thing existed. There should be no reason to make assignment between variables of the same type anything else than a direct copy.
If the incoming new_width and new_height keep their values until they change, then this comparison should not have any issues. But if they are calculated before every call they might change their value, depending on how the calculation is done. So it's not only this function that needs to be checked.
The C 2011 standard says that calculations may use bigger precision than the format you assign to, but nothing specific about assigning a variable to another. So the only imprecision should be in the calculation stage. The "simple assignment" part (6.5.16.1) says:
In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
So if the types already match, there should be no need for conversion.
So, simply put: if you don't recalculate the incoming value on every call the comparison for equality should hold true. But is there really a case where your framebuffers are sized as floats and not integers?
In the case you mentioned it is safe to use == to compare because of the following lines at the end of the function:
current_width = new_width;
current_height = new_height;
any change to new_width or new_height will fail the if statement and you get the behavior you wanted.
abs() function usually is used when there is one variable float which is assigned dynamically in the program and one constant float which you want to use as a reference. Something like:
bool isEqual(float first, float second)
{
if(fabs(first-second)<0.0001)
return true;
return false;
}
int main()
{
float x = (float) 1 / 3;
if(isEqual(x,0.3333))
printf("It is equal\n");
else
printf("It is not equal\n");
}
Have a look here for how to compare two floats.
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Find the test with "ULP, he said nervously". You can compare the floats as ints but have a look at how it's been done in the article ie (I hope I'm not breaching any licensing here, if so please delete the code that follows it's not mine)
bool AlmostEqualUlps(float A, float B, int maxUlpsDiff){
Float_t uA(A);
Float_t uB(B);
// Different signs means they do not match.
if (uA.Negative() != uB.Negative()) {
// Check for equality to make sure +0==-0
if (A == B) {
return true;
}
return false;
}
// Find the difference in ULPs.
int ulpsDiff = abs(uA.i - uB.i);
if (ulpsDiff <= maxUlpsDiff) {
return true;
}
return false;
}
Please read the rest of that article, it's really good.

What is the meaning of '==' in C?

What is the meaning of == and how does it differ from =?
How do I know which one to use?
== is a test for equality. = is an assignment.
Any good C book should cover this (fairly early on in the book I would imagine).
For example:
int i = 3; // sets i to 3.
if (i == 3) printf("i is 3\n"); // prints it.
Just watch out for the heinous:
if (i = 4) { }
which is valid C and frequently catches people out. This actually assigns 4 to the variable i and uses that as the truth value in the if statement. This leads a lot of people to use the uglier but safer:
if (4 == i) {}
which, if you accidentally use = instead of ==, is a compile-time error rather than something that will bite you on the backside while your program is running :-)
The logical-or operator is two vertical bar characters, one after the other, not a single character. Here it is lined up with a logical-and, and a variable called b4:
||
&&
b4
No magic there.
a == b is a test if a and b are equal.
a = b is called an assignment, which means to set the variable a to having the same value as b.
(You type | with Shift-\ in the US keyboard layout.)
== tests equality
= assigns a value
neither are related to ||
I might add that in Finnish and Swedish keyboards. Pipe symbol; |; of OR is AltGr (the right alt) and < key. IF you are using Mac on the other hand it is Alt-7 key.
Gave me a lot of sweat when I first started typing on these keyboards.
Now that you know the difference between '==' and '=", let me put you some words of caution. Although '==' is used as a standard test of equality between comparable variables and '=' used as an internally type-casted assignment, the following programming error is quiet common.
In the below example and similar codes, '=' is know as "Always true" conditional operator.
#include<stdio.h>
int main()
{
int i = 10, j = 20;
if ( i = j )
printf("Equal\n");
else
printf("NOT Equal\n");
return 0;
}
So, the word of caution is "Never use '=' in if statements, unless you have something evil in your mind."

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

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
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?
I like my ifs to make sense when read aloud:
if (is_it_happening) ...
if (number_of_sheep != 0) ...
if (pointer_to_something != NULL) ...
I prefer
if (var != 0)
It's easier to read/understand. Since you write the code once but read quite a few times, easy reading is more important than easy writing.
It's quite simple. if( var ) tests for truthiness. if( var != 0 ) tests that it's not the number 0. THEY ARE NOT INTERCHANGABLE! There are three reasons.
First, using if( var != 0 ) to test for truth is more complicated. There's simply more there to read and understand. You have to grok that != and 0 is the idiom for "is true". Lacking a distinctive visual pattern, you have to do a little more studying to know that it's not the same as if( var == 0). This is a thin distinction, but worth mentioning. The fact that the if( 0 != var ) style exists gives credence. Better to just eliminate the problem and use if( var ) for truthiness.
Second, and more importantly, the intent must be clear. Are you testing for truth or are you testing for a number (or lack thereof)? if( var ) is testing for truth, if( var != 0 ) is testing a number. To determine anything else requires having knowledge of the author's style, which we must assume the maintenance programmer does not.
Third, there is an assumption here about the value of true and false and numeric operators which might work out in some languages and not in others. In Perl, and I think Javascript, too, empty string is false. A lot of operators return empty string for false. So testing truth with if( var != 0 ) leads to a warning. It becomes more stark when you do something more naive like if( var == 1 ) to mean truth, a clearly dangerous assumption. I have seem many junior programmers write that and in turn written functions that return odd, but true, numbers to punish this sort of thing. Or when I'm in a giving mood, I've sanitized my return value with return var ? 1 : 0.
In a related note, Perl will return the last evaluated expression from a subroutine, so it's not necessary to actually write return. Combine this with the idea people have that explicit return is slower and you get a lot of people abusing this fact.
sub set {
my( $self, $key, $value ) = #_;
$self->{$key} = $value;
}
set will return $value. Was that intended? I don't know. What I do know is someone will start relying on it. And the maintenance programmer won't know if they can change it. So I like to explicitly put a return in every non-trivial subroutine.
sub set {
my( $self, $key, $value ) = #_;
$self->{$key} = $value;
return;
}
In that case I decided set will return nothing for the time being and that decision will be quite clear to both the reader and the user.
if (var)
Less to type, as long as you're sure you're not testing the wrong thing.
I prefer explicit tests unless the result inside the parentheses is a explicit boolean. The phrase "if (1)", while syntactically and semantically correct in terms of the language, is not logical. It should be true or false, not cast automatically.
I prefer readable logical code to less typing any day.
I also despise vehemently code of the form:
if (gotError == FALSE) ...
if (isComplete == TRUE) ...
If the boolean value is properly named (and it should be), the right way to do that is:
if (!gotError) ...
if (isComplete) ...
That's because (using reductio ad absurdum) boolVal == TRUE is simply another boolean value, so where do you stop?
if (isComplete == TRUE) ...
if ((isComplete == TRUE) == TRUE) ...
if (((isComplete == TRUE) == TRUE) == TRUE) ...
if ((((isComplete == TRUE) == TRUE) == TRUE) == TRUE)...
And so on, ad infinitum.
I would say that if you are comparing a true integer, then never do an implicit conversion to boolean, as it implies a different meaning to the variable.
But then again that style is so popular is probably isn't too big of a deal, but from my work with C#, I write my C++ code in this style:
Boolean or int that is basicaly a boolean:
if (val)
True integer with more than true/false being important:
if (val != 0)
Pointer of some kind:
if (val != NULL)
But as many people will say about coding styles that make no functional difference, it is probably best of all to be consistent, and if you are working with existing code, be consistent with that code.
In Perl if (defined $var and $var ne '') and if( $var) are NOT equivalent. Try it with $var=0. Conversely if you test on $var!=0 all strings that cannot be converted to numbers will fail the test (with a warning if you have them on).
So you must know exactly what your variable contains (number or string, whether it can be undef) so you can test accordingly.
I usually just write if( $var) and let Perl take care it. I believe that's easier to read, and that's the most common style in Perl.
Very often, actually, the proper test ends up being if( defined $var). That's where perl's new (in 5.10) // operator comes in handy. $var= $val // $default or often $var //= $default, where $var will receive $default only if $val (resp $var) is undef.
In Javascript (I don't know about other dynamic languages)
if (x)
and
if (x != 0)
mean different things. I will use the former when the I expect x to hold a reference to an object or string that should not be zero length. Its a well known enough idiom.
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.
}
I go with readability like most people, I like being able to scan my code and read it without having to think too much, it goes hand in hand though with well named variable names. If your variable names make it sound like it should be a plain if(isPurchasable) then I go with it however it referes to a number or date or similar fasion I use if(stock > 0).
Having to write a comment for an if statement too me is a horrible idea if the expression is so simple, an if statement like below though I can see why comments should be used.
if(isPurchasable && stock > 0 && credit >= cost && !reserved) {
// Checks to see if customer can purchase product.
}
For numeric value scalars, I tend to write if ( $num_foo ) when $num_foo is in my control. If it’s user input or passed in from outside I either numify it first or spell out the test explicitly. It depends on a lot of factors. The main criterion is when and how it’s convenient to deal with undefined values, in order to avoid warnings.
To test for non-empty string, I used to write if ( $foo ) because the correct incantation is just way too much typing:
if ( defined $foo and length $foo )
But I wasn’t satisfied with this state of affairs so I instigated a change of behaviour for length undef in Perl 5.12, which throws a warning and returns 0 up to Perl 5.10 inclusive. In 5.12 it will just silently return undef. Therefore in non-boolean contexts you still get a warning, it just happens after the length call is evaluated rather than before. But in boolean contexts, there is no warning, so checking for a non-empty string is much easier to do correctly:
if ( length $foo )
I have a bunch ways of doing it:
for booleans:
if (x)
for ints:
if (x != 0) // always compare, never assume true/false on int values
for pointers:
if (x /* != 0 */) // I've always done this, not sure where I picked it up but I like it
These days, I think it's nicer to have a function call which describes what the logic actually means within the if statement
EDIT: Note, the 0 (intsead of NULL) is because I mainly use C++ these days
I'm surprised nobody's mentioned the other option, which the coding standards at a past employer of mine advocated:
if( 0 != x );
Where the constant was always listed first (especially more important with comparisons as they occasionally get typo'd to assignments - the source of many a bug)
It's the style I've used ever since in my C / Perl / C++ / VB.Net since (obviously the point becomes moot in C# whihc doesn't actually allow the if (x) scenario (unless x is actually a boolean, of course).
In C# it has been made explicitly illegal to write
if(x){}
unless x is a boolean type. There is no implicit conversion to bool from most other types.
I used this form a lot writing JavaScript, PHP and such to check for non null. But then again, I did get a few (easily detectable) bugs from it... I guess we are better off without it.
When using it on boolean variables, I strongly believe in easily readable names. I usually name boolean variables used like that with names beginning with "is", "has" or something similar.
I generally prefer if (var) or if ($var) if var is used as a boolean, even if there isn't any such type in the language.
I very much dislike constructs like if (!strcmp(...)) or if (var == true). The first tries to be too smart, the second too dumb -- although it scales well to if ((var == true) == true), ... ;-)
Some languages, like Perl and C++, provide extra or even user defined interpretations of trueness. If the conversion to a boolean seems too magic, remember it's basically just an is_true(var) or var.booleanValue(), or something like that behind the scene, just a more concise syntax.
Related to your question, I like to formulate conditions in a positive way. Instead of
if (!condition) {
g();
}
else {
f();
}
I prefer
if (condition) {
f();
}
else {
g();
}
Even if there is only a single branch, and the condition is not terribly simple. (An indication for that is the need for a comment.) For example, instead of
// explain reason for condition here
if (!condition) {
f();
}
I prefer to phrase it as
if (condition) {
// explain condition here
}
else {
f();
}
To my way of thinking, simplicity is best.
The simpler you make the code, the better. Also, the less likely you'll make mistakes. Therefore, I would use
if(var)
But in the end, you should use what works best for your own way of thinking.
I don't always manage it, but I try to use
if (0 != var)
so it matches the defensive style
if (0 == var)
If you've got an int-bool in C that already holds a flag (and not a count), and you're testing it with "if (var != 0)", where does it end? Wouldn't "if ((var != 0) != 0)" be even better? :-)
I prefer a bare:
if ($canDo) {
}
instead of something like:
if ($canDo == true) {
}
Where a conditional is at all tricky, I comment it either explicitly with a comment, or implicitly with a good variable name. I also try to be very explicit when setting a boolean variable, preferring:
my($canDo) = !0;
to
my($canDo) = 1;
The latter is confusing; why assign a discrete value to a boolean?
Given Perl's many meanings to "evaluates to true", though, I can see why being more explicit is more practical in the long run. Still, one of the things I most like about Perl is its natural linguistic fluidity, and I prefer in my code to stick to that (leaving the comments and variable names to further clarify things, if needed).
VBScript? Well this bit of code declares a Variant, so bFlag is zero, which is effectively a False.
Dim bFlag
If bFlag Then
I don't like that. So even in VB, with the option of more specific declarations, I find myself being explicit no matter what the type.
Dim bFlag As Boolean
If bFlag = False Then
The other issue related to variable naming rules. If you're using an Hungarian-influenced regime, then you can tell visually that a given variable is boolean, so being specific about whether it's true or false is less of an issue. If, however, you're using some other variable naming technque, or worse, naming in an ad hoc way, then being specific about what's being tested for is appropriate.
Very often I use:
if(x) {
DoSomething;
DoSomething2;
}
Because this is less writing, and book which reading said:
Few good programmers use form if(x!=0), they use if(x).
But sometimes use and other form:
if(x!=0)
HNY! :-)
I find that if(X) { /* ... */ } is much easier to read (in C, at least).
If i don't expect anyone else to read the code, I'd us the short one.
If I expect someone to actually read my code, I would consider using the long form for readability.
I like Python constructions:
if var:
return "I like the way I do it!"
It's just for example ;-)
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.
In my opinion, if (var != 0) is better.

Resources