Reputation: 5030
I have seen some codes that perform variable assignment in the if
condition, for example:
if((data->symStem = sym.isStem())==TRUE) //if condition
{
// do something
}
To my understanding, in the if condition above, sym.isStem()
is first assigned to data->symStem
, and thereafter, the equality condition (for sym.isStem()
or data->sysStem
) is evaluated. Please correct me if there is something wrong.
I wonder if there is any particular reason to do so except that the codes are more compact.
Upvotes: 1
Views: 217
Reputation: 62563
In C++17, this gets a certain twist - now you are not only allowed to assign variables, you are also allowed to create and initialize variables in the if
condition (it is called if statement with initializer):
if (int a = foo(); a != 0) {
//...
}
That has a benefit of being able to introduce scoped variables without having to put new set of artifical braces around it, like pre-C++17 you'd have to do
{
int a = foo();
if (a != 0) {
//...
}
}
Upvotes: 1
Reputation: 122133
Assignment is typically implemented as
struct foo {
foo& operator=(const foo& other) {
// do the assignment
return *this;
}
};
and the reason is to allow chaining as in your example. There is really not much more to it than saving a line of code.
Upvotes: 0
Reputation: 36463
No, there's no reason to do it other than writing it in 1 line vs 2 lines.
Upvotes: 3