Two ways to compare a variable in a condition statement

Hello
Imagine, we have to compare whether variable is equal 1. In this case variable is called "flag". There are two ways(even more) to achieve this task.
First one is here:
 if(flag == 1) 
Second one is following:
 if(1 == flag) 
At the first glance both ways are the same, but really one of them is better. Do you know which one is better and why?

Let's assume, that one equal sign has been skipped. What would happen in first case, and what in seceond case? In first case compiler does not report an error. In addition flag is set to true, therefore the output of the program is not the same, which we would expect. Is not it?

In second case compiler report an error because this assignment is not possible. Therefore this sort of bug can be solved immediately. Definitely second method is better.
This simple trick makes the program more robustness. All good program should be written with good practices, such as example above. This method can be successfully applied for checking whether variable is not equal:
 if(1 != flag) 
Variable is less or equal:
 if(1 >= flag) 
Variable is greater or equal:
 if(1 <= flag) 
I hope it is useful for you.
Which way do you use? Let's give me an answear in comment section below.

Well that is about all for now.

Comments

Popular posts from this blog

Semihosting

How long the piece of code is executed?