Reputation: 960
Why does this C++ code print what it prints?
#include <vector>
#include <stdio.h>
int p(const char *x) {
printf("%s\n", x);
return 0;
}
int main()
{
if (p("LEFT") == p("RIGHT")) ;
std::vector<int> v1;
v1.push_back(1);
std::vector<int>::iterator it = v1.erase(v1.begin());
if (it == v1.end())
printf("OK\n");
else
printf("FAIL\n");
std::vector<int> v2;
v2.push_back(1);
if (v2.erase(v2.begin()) == v2.end())
printf("OK\n");
else
printf("FAIL\n");
return 0;
}
I'm confused about the OK/FAIL part. This is in contradiction with the LEFT/RIGHT part. What's happening here?
The output for me is:
LEFT
RIGHT
OK
FAIL
Upvotes: 1
Views: 127
Reputation: 258618
Associativity has nothing to do with order of evaluation.
In fact, you're invoking unspecified behavior. You can't tell which part of ==
will evaluate first.
Think about this:
int x; // x is 0 initially
int foo()
{
x++;
return x;
}
int goo()
{
return x;
}
int main()
{
bool b = foo() == goo();
}
If foo
(returns 1) evaluates first, b
will be true
(goo
will return 1).
If goo
(returns 0) evaluates first, b
will be false
(foo
will return 1).
Upvotes: 7
Reputation: 30035
It being left associative does not affect the order in which its parameters are evaluated which is unspecifed by the language. It simply means that if you write "a == b == c" then it will interpret it as ((a==b) == c). But it can calculate a, b and c in advance and in any order it likes.
Upvotes: 3