A safest way to check value using 'Equal To' (==) operator in C

By: IncludeHelp, on 24 JAN 2017

Let's consider the following statement

if(result==0)
{
    statements;
}

Here, if value of result is equal to 0 then statements will be executed.

But, sometimes, by mistake programmers forget to use "Equal To" and use "Assignment Operator" (=).

Then, what will happen?

Let suppose, we use "=" instead of "==", then the statement will be if(result=0), so condition will be false because 0 is assigning into result and throughout all program value of result will be 0 until other statement do not update the value.

Safest way to check

Put the value (Remember, only value) at the left side of "Equal To" Operator and variable at the right side. Consider the below statement:

if(0==result)
{
    statements;
}

Here, 0 and result are comparing and if the condition is true statements will be executed.

How this way is safe?

If by mistake, we forget to use "==" and we use "=" then compiler will through an error because a variable's value cannot be assigned into a value (literal).




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.