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?
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#?
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.
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.
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.
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).
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