Assignment, Comparison, and a Mistake You’ll Probably Make

Don’t confuse testing the is-equal-to operator (==) with the assignment operator (=). This expression asks the musical question “Is musicians equal to 4?”:

musicians == 4    // comparison

The expression has the value true or false. This expression assigns the value 4 to musicians:

musicians = 4     // assignment

The whole expression, in this case, has the value 4 because that’s the value of the left side.

The flexible design of the for loop creates an interesting opportunity for error. If you accidentally drop an equals sign (=) from the == operator and use an assignment expression instead of a relational expression for the test part of a for loop, you still produce valid code. That’s ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.