Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between if(CONST==variable) or if(variable==CONST)?

Tags:

c

Is there a difference in the order of the comparison operator?

#define CONST_VALUE 5

int variable;

...

if ( variable == CONST_VALUE )   // Method 1
...

OR

if ( CONST_VALUE == variable )   // Method 2
...

Is this simply a matter of preference or is there a compelling reason for a particular comparison order?

like image 732
semaj Avatar asked Oct 26 '09 18:10

semaj


People also ask

What is the difference between if ($ var == 5 vs IF 5 == $var?

no difference, it is an old habit to avoid if(a=5) in c/c++. These questions/answers are about the same: (0 == variable) or (null == obj): An outdated practice in C#?

What is the difference between a variable and a constant in computer programming?

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. Variables are specially written in letters or symbols.

How does constant defined by const differ from the constant defined by the pre processor statement define explain with an example?

Long story short: CONSTs are handled by the compiler, where as #DEFINEs are handled by the pre-processor. The big advantage of const over #define is type checking. #defines can't be type checked, so this can cause problems when trying to determine the data type.

What is the use of const in C?

The const keyword allows a programmer to tell the compiler that a particular variable should not be modified after the initial assignment in its declaration.


1 Answers

The reason some people use method 2 is because you'll get a compiler error if you mistype a = in place of the ==.

However, you'll have people (like me) who will still use method 1 because they find it more readable and if there is an error, it will be detected during testing (or, in some cases, static analysis of the code).

like image 193
Thomas Owens Avatar answered Jan 04 '23 04:01

Thomas Owens