Consider:
if (a=5) {
/* do something */
}
How does the assignment work as a condition?
Is it based on non-zero value of l-value?
It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it's '==' or '==='. To assign a value to a variable it's '=' Submitted by Clarisse.
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)
An Assignment statement is a statement that is used to set a value to the variable name in a program. Assignment statement allows a variable to hold different types of values during its program lifespan.
if (y > z) x = y; else x = z; The following expression calls the function printf , which receives the value of the variable c , if c evaluates to a digit. Otherwise, printf receives the character constant 'x' .
[5.17/1]
There are several assignment operators, all of which group right-to-left. All require a modifiable lvalue as their left operand, and the type of an assignment expression is that of its left operand. The result of the assignment operation is the value stored in the left operand after the assignment has taken place; 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 the expression, implicitly converted tobool
for statements other thanswitch
. [..]
A conversion to bool
takes place.
[4.12/1]
An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of typebool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
.
5
converts to boolean true
.
[6.4.1/1]
If the condition (6.4) yields true the first substatement is executed. [..]
true
is treated as an if
statement success.
[6.5.16/3]
An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue. [..]
The result of the expression a = 5
is 5
.
[6.8.4.1/2]
In both forms, the first substatement is executed if the expression compares unequal to 0. [..]
5
is treated as an if
statement success.
Code like this is almost always a mistake; the author likely intended if (a == 5) {}
. However, sometimes it is deliberate. You may see code like this:
if (x = foo()) {
cout << "I set x to the result of foo(), which is truthy";
// ... stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With