Reputation: 949
Which is more efficient
if(!var_name)
or
if(var_name == NULL)
Upvotes: 1
Views: 766
Reputation:
Both are equivalent in the view of efficiency but later is better for readability,which also play crucial role in coding.
Upvotes: 0
Reputation: 25537
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)
Upvotes: 0
Reputation: 5623
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.
Upvotes: 5
Reputation: 69480
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.
Upvotes: 16
Reputation: 14077
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.
Upvotes: 0
Reputation: 52334
I would not use a compiler which generates different code for performance sensitive stuff.
Upvotes: -1
Reputation:
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.
Upvotes: 7