In many languages assignments are legal in conditions. I never understood the reason behind this. Why would you write:
if (var1 = var2) { ... }
instead of:
var1 = var2; if (var1) { ... }
Can we put assignment operator in if condition? Yes you can put assignment operator (=) inside if conditional statement(C/C++) and its boolean type will be always evaluated to true since it will generate side effect to variables inside in it.
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.
An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. When the statement is executed, the expression is evaluated and the resulting value is stored in the target.
Yes, you can assign the value of variable inside if.
It's more useful for loops than if statements.
while( var = GetNext() ) { ...do something with var }
Which would otherwise have to be written
var = GetNext(); while( var ) { ...do something var = GetNext(); }
I find it most useful in chains of actions which often involve error detection, etc.
if ((rc = first_check(arg1, arg2)) != 0) { report error based on rc } else if ((rc = second_check(arg2, arg3)) != 0) { report error based on new rc } else if ((rc = third_check(arg3, arg4)) != 0) { report error based on new rc } else { do what you really wanted to do }
The alternative (not using the assignment in the condition) is:
rc = first_check(arg1, arg2); if (rc != 0) { report error based on rc } else { rc = second_check(arg2, arg3); if (rc != 0) { report error based on new rc } else { rc = third_check(arg3, arg4); if (rc != 0) { report error based on new rc } else { do what you really wanted to do } } }
With protracted error checking, the alternative can run off the RHS of the page whereas the assignment-in-conditional version does not do that.
The error checks could also be 'actions' — first_action()
, second_action()
, third_action()
— of course, rather than just checks. That is, they could be checked steps in the process that the function is managing. (Most often in the code I work with, the functions are along the lines of pre-condition checks, or memory allocations needed for the function to work, or along similar lines).
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