I noticed for a while now the following syntax in some of our code:
if( NULL == var){ //... }
or
if( 0 == var){ //... }
and similar things.
Can someone please explain why did the person who wrote this choose this notation instead of the common var == 0
way)?
Is it a matter of style, or does it somehow affect performance?
The number before an alphabet (variable) is called a constant. Variable : A symbol which takes various numerical values is called a variable. The alphabet after a number (constant) is called a variable. In the formulas d = 2r; 2 is a constant whereas, r and d are variables.
Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.
What is the Difference between Constant and Variables? A constant does not change its value over time. A variable, on the other hand, changes its value dependent on the equation. Constants are usually written in numbers.
A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration.
It's a mechanism to avoid mistakes like this:
if ( var = NULL ) { // ... }
If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes:
if ( NULL = var ) { // not legal, won't compile // ... }
Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing.
Edit:
As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, gcc -Wall
will give you the following:
warning: suggest parentheses around assignment used as truth value
You should always enable warnings on your compiler, it is the cheapest way to find errors.
Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With