Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why put the constant before the variable in a comparison?

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?

like image 708
RomanM Avatar asked Dec 16 '08 03:12

RomanM


People also ask

Do constants or variables go first?

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.

Why would you use a constant over a variable?

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 are constants in comparison to variables?

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.

When Should a variable be constant?

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.


1 Answers

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.

like image 136
Robert Gamble Avatar answered Oct 04 '22 14:10

Robert Gamble