`x ? 1 : 0` became 40, undefined behavior?

c++, undefined-behavior

Solution

You don't initialize `this->x` in your move constructor. I'm pretty sure conditionals on uninitialized variables are undefined behaviour.

#include <cstdio>
#include <queue>

class Obj {
    bool x;
public:
    Obj(): x(true) {}
    Obj(Obj&& o) : x(true) { // Hi!
        o.x = false;
    }
    ~Obj() {
        if(x) {
            std::puts("Here");
            std::printf("%d\n", x ? 1 : 0);
        }
    }
};

int main() {
    std::queue<Obj> q;
    q.push(Obj());
    q.pop();
}

The above works as expected (prints "Here 1").

Problem

I wrote this code: ``` #include <cstdio> #include <queue> class Obj { bool x; public: Obj(): x(true) {} Obj(Obj&& o) { o.x = false; } ~Obj() { if(x) { std::puts("Here"); std::printf("%d\n", x ? 1 : 0); } } }; int main() { std::queue<Obj> q; q.push(Obj()); q.pop(); } ``` With optimization enabled, I got a confusing result: ``` Here 40 ``` And the number can be `160`, `24`, `96` or `104` by executing the program in different ways. On Ideone nothing is printed. It must have been an undefined behavior. But I can't figure out what's wrong. Can you point out my mistake? Note: My compiler is GCC 4.8.1, and my operating system is Windows 7.

Original source