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
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:
If
foo(returns 1) evaluates first,bwill betrue(goowill return 1).If
goo(returns 0) evaluates first,bwill befalse(foowill return 1).