I use python a lot. So, by accidentally I can type this code and compiler won't give me a error:
#include <iostream>
using namespace std;
int main() {
cout << (1 <= 2 <= 1);
}
In python, and some other languages, the expression a <= b <= c is equivalent to a <= b and b <= c. But in c++, this code produces 1 (true).
Why it compiles successfully? And why it prints 1?
Hope this blog will prevent someone from possible future mistakes.









Thanks, I will know it :).
Use -Wall, Luke.
Thanks, very useful.
By the way, do you use PyQt? What is your preferred method of making a static build of an application?
I use pascal a lot. So, by accidentally I can type this code and compiler won't give me a error:
In pascal, and some other languages, the expression a = 1 is equivalent to check if the variable a has the value 1. It must be false since a = 0 by default, but in c++, this code produces 1 (true).
Why it compiles successfully? And why it prints 1?
cout << (a = 1);gets split asa = 1followed bycout << a;.a = 1assigns the value 1 toa, and thencout << a;prints the value ofa. therefore the output comes as 1.to do what u want, change
cout << (a = 1);tocout << (a == 1);. the output will be 0.It's rather a design decision. In C++ the '=' operator is usually defined as follows (yeah, it's a simplification of what really can happen):
What happens there? We assign
othertothisand return the reference tothis. This way, you can write:It is interpreted as
a = (b = (c = 42))and means: assign42toc, return reference toc; assign value ofctob, return reference tob; assign value ofbtoa, return reference toa; this way all three variables are now equal to 42. But... yes, it leads to some trouble. Thus some people tend to write something like(that is, a non-variable element is on the left-hand side). If you accidentally omit one
=, you'll get a compilation error.Reds cannot into sarcasm...
It is evaluated left to right so when first condition returns 1 it is left with 1<=1 which also returns 1.