Places where assignment operator(=) is used logically incorrectly instead of comparison operator(==) in C++. Logical error e.g. if (a=10) it should be if (a==10). Can you help me list all such cases?

Praveen Gupta
Praveen Gupta used Ask the Experts™
on
I'm doing a C++ compiler project where I need to flag warnings at places where assignment operator (`=`) can be used wrongly instead of the comparison operator (`==`)...e.g
while doing comparison in `if` statement , to check variable `a` as `10` sometimes we wrongly type if(`a`= `10`), which will result in `if` statement always `true` whereas I wanted to be `true` only if `a` is `10`. Some of the cases I can think of are :
1. `if(var = a)`, logically it should be `if( var==a )`
2. `while(var = a )`
3. `for(;var=a;)`
4. `do{}while(var=a)`
5. `var=a? "some XYZ": "some ABC"`

Can you please help me with the more cases where this logical error can occur, where the user was supposed to use `==` and by mistake `=` was used?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fabrice LambertConsulting
Distinguished Expert 2017
Commented:
Hi,

On a return statement:
bool isTen(int num)
{
    return num = 10;    // should be: num == 10;
}

Open in new window

Application Developer
Commented:
For instances where you have a variable compared to a constant, change it to:

if (constant == variable)

ie.

if (0 == var)

if you have a typo in this, ie only having one = symbol, it won't compile.  You just have to get into the habit of coding like this.
Fabrice LambertConsulting
Distinguished Expert 2017

Commented:
Solutions provided

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial