Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c++ what does if(a=b) mean? versus if(a==b)

Tags:

c++

Probably been answered, but could not find it.

In c++ what does

if(a=b)

mean? versus

if(a==b)

I just spent two hours debugging to find that

if(a=b)

compiles as

a=b

Why does compiler not flag

if(a=b)

as an error?

like image 375
Chris Molloy Avatar asked Jan 01 '23 05:01

Chris Molloy


1 Answers

In c++ what does if(a=b) mean?

a=b is an assignment expression. If the type of a is primitive, or if the assignment operator is generated by the compiler, then the effect of such assignment is that the value of a is modified to match b. Result of the assignment will be lvalue referring to a.

If the operator is user defined, then it can technically have any behaviour, but it is conventional to conform to the expectations by doing similar modification and return of the left operand.

The returned value is converted to bool which affects whether the following statement is executed.

versus

if(a==b)

a==b is an equality comparison expression. Nothing is assigned. If the types are primitive, or if the comparison operator is generated by the compiler, then the result will be true when the operands are equal and otherwise false.

If the operator is user defined, then it can technically have any behaviour, but it is conventional to conform to the expectations by doing similar equality comparison.

Why does compiler not flag

if(a=b)

as an error?

Because it is a well-formed expression (fragment) as long as a is assignable with b.

if(a=b) is a conventional pattern to express the operation of setting value of a variable, and having conditional behaviour depending on the new value.

Some compilers do optionally "flag" it with a warning.

like image 66
eerorika Avatar answered Jan 13 '23 13:01

eerorika