Use assignment as a condition expression?

Consider:

if (a=5) { /* do something */ } 

How does the task work as a condition?

Is it based on a nonzero l-value?

+4
source share
4 answers

C ++ - ISO / IEC 14882: 2003 (E)

[5.17/1] There are several assignment operators, each of which is from right to left. They all require a modifiable lvalue as their left operand, and the type of assignment expression is its left operand. The result of the assignment operation is the value stored in the left part of the operand after the job ; the result is an lvalue.

The result of the expression a = 5 is 5 .

[6.4/4] [..] The value of a condition that is an expression is the value of an expression implicitly converted to bool for statements other than switch . [..]

Converts to bool .

[4.12/1] The value of arithmetic, enumeration, pointer, or pointer to member type can be converted to rvalue of type bool . A null value, a null pointer value, or a pointer value of a null element is converted to false ; any other value is converted to true .

5 converts to boolean true .

[6.4.1/1] If condition (6.4) gives a true first, a substitution is performed. [..]

true seen as an if success.


C - ISO / IEC 9899: 1999 (E)

[6.5.16/3] The assignment operator stores the value in the object indicated by the left operand. The assignment expression has the value of the left operand after the assignment , but is not an lvalue value. [..]

The result of the expression a = 5 is 5 .

[6.8.4.1/2] In both forms, the first subproblem is executed if the expression is compared not equal to 0 . [..]

5 seen as an if success.


General

Code like this is almost always a mistake; the author most likely suggested if (a == 5) {} . However, sometimes this is intentional. You can see the following code:

 if (x = foo()) { cout << "I set x to the result of foo(), which is truthy"; // ... stuff } 
+20
source

if(a=x) equivalent to if(x) in addition to a assigned to x . Therefore, if the expression x evaluates to a non-zero value, then if(x) just becomes if(true) . Otherwise, it becomes if(false) .

In your case, since x = 5 , this means that f(a=5) equivalent to if(true) in addition to a assigned 5 .

+1
source

Each nonzero value will be considered true .

So, some people will suggest you write

 5 == a 

to avoid the error == = .

+1
source

Yes, it is based on the zero / non-zero value that is assigned to a. For some people (including me), it is also believed that bad practice has expressions with side effects in your code, so the above code fragment will preferably be written as something like

 a = 5; ... if (a != 0) { ... } 
0
source

All Articles