In C++, operators can have return values just like functions. Whether you can use an expression as a conditional entirely depends on what they return. For that, you'll have to consult the documentation.
In an assignment: a = b
, the default behavior is to return whatever the value of b
is; this is so that chain assignments like a = b = c = 5
would work.
That expression would be equivalent to a = (b = (c = 5))
. c = 5
will return 5, the expression becomes a = (b = 5)
, and b = 5
returns 5, and so once again, the expression becomes a = 5
, thus assigning 5 to a
, b
, and c
.
A stream object can be directly evaluated as a bool because it was designed to do so via the overridden bool operator.
In the case of a >>
operator on a stream object, that operator is overridden to return the stream object, so in something like: while (cin >> userInput)
, cin >> userInput
returns cin
, which will yield either true or false.
Is this good practice?
I'm still a university student, so grains of salt needs to be taken with this. In the case of a stream, I'd say it's good practice as this is a well known pattern to do things. Most people can tell what you intend to do straightaway whereas alternatives aren't as clear.
As for the assignment, I'm leaning towards no, but it depends on who's reading your code and what you're doing. If you use it too much, it may become hard to differentiate between things like if (userInput = 5)
and if (userInput == 5)
, making bugs hard to find.