Home » Programming Tips & Tricks » C - Tips & Tricks

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






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.
Close