Which is more efficient
if(!var_name)
or
if(var_name == NULL)
Which is more efficient
if(!var_name)
or
if(var_name == NULL)
It doesn't matter. Both will be very efficient, no matter what compiler you use, and for most compilers will compile to exactly the same code. If this is of genuine concern to you, take a look at the assembly/machine code emitted by your specific compiler.
It does not matter.
Changing this would be micro optimisation and unlikely to change the performance of your app (unless you have actualy checked this is the bottle neck). Other then that I would bet the compiler would change this statement into the best one (if it mattered), so I would use the syntax that you prefer.
I would not use a compiler which generates different code for performance sensitive stuff.
In case var_name is a pointer and you're compiling for some embedded system with a crappy non-optimizing compiler, var_name == NULL
will be faster, because a cast to boolean followed by negation followed by comparison to true will be slower than plain value comparison. In case of about every single other compiler they will get optimized away to the same code.
Both will compile to the same code. Your choice of which to use should depend on which is most readable.
This version:
if(var_name == NULL)
should only be used when var_name
is a pointer, otherwise you will confuse anyone who reads your code in the future. Some compilers might complain if you use this on a non-pointer.
This one:
if(!var_name)
should be used in cases when you are logically treating var_name
as a boolean (true/false) value. This can include when var_name
is a pointer, since NULL
is the value for "false" or undefined pointers.
If var_name
is an integer, then I would choose a third option:
if(var_name == 0)
as I find it expresses intent more clearly.
if(var_name == NULL)
is more efficient because the guy (or your own self in the future) who reads that code will immediately see that:
var_name
is a pointeron the other case the intent and variable type is completely ambiguous. Is it a boolean? is it an int? Is it a pointer? are you checking against zero? or a true/false condition?
These questions are answered right away with the notation above, and it should be used whenever the intent is null checking a pointer.
If 'var' is of a UDT, then the choice of which to use would be guided more by which of these operators the class offers rather than efficiency (which I believe is answered by most of the responses above)