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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.