An Unfortunate Assignment

This program may not behave as you expect.

#include <iostream> using namespace std; int main() { int n; /* Read and test a value. */ cin >> n; if(n = 5) cout << "You entered five!" << endl; else cout << "You FAILED to enter five!" << endl; cout << "Your number: " << n << endl; }

Many compilers will issue a warning for this code, though sometimes the message is a difficult to decipher. (In C++, it's usually a good idea to find the cause of all compiler warning messages.) This code is legal C++ because of several language rules, most of which we've mentioned before:

One other odd consequence of the conversion rule might be of interest to any of you who has experience with the wonderful Python languge. In Python, an expression like 7 > 6 > 5 is legal and evaluates to true, which is quite nice. In Java, 7 > 6 > 5 is not legal, which is quite reasonable. In C++, 7 > 6 > 5 is legal and evaluates to false, which is quite annoying. I'll go into the reasons if you ask, but I'm not so worried about you stumbling onto this one by accident.