(Why) is using an uninitialized variable undefined behavior?

Yes this behavior is undefined but for different reasons than most people are aware of. First, using an unitialized value is by itself not undefined behavior, but the value is simply indeterminate. Accessing this then is UB if the value happens to be a trap representation for the type. Unsigned types rarely have trap representations, … Read more

Does “Undefined Behavior” really permit *anything* to happen? [duplicate]

Yes, it permits anything to happen. The note is just giving examples. The definition is pretty clear: Undefined behavior: behavior for which this International Standard imposes no requirements. Frequent point of confusion: You should understand that “no requirement” also means means the implementation is NOT required to leave the behavior undefined or do something bizarre/nondeterministic! … Read more

Is passing a C++ object into its own constructor legal?

This is not undefined behavior. Although foo is uninitialized, you are using it a way that is allowed by the standard. After space is allocated for an object but before it is fully initialized, you are allowed to use it limited ways. Both binding a reference to that variable and taking its address are allowed. … Read more

How did I get a value larger than 8 bits in size from an 8-bit integer?

This is a compiler bug. Although getting impossible results for undefined behaviour is a valid consequence, there is actually no undefined behaviour in your code. What’s happening is that the compiler thinks the behaviour is undefined, and optimises accordingly. If c is defined as int8_t, and int8_t promotes to int, then c– is supposed to … Read more

When does invoking a member function on a null instance result in undefined behavior?

Both (a) and (b) result in undefined behavior. It’s always undefined behavior to call a member function through a null pointer. If the function is static, it’s technically undefined as well, but there’s some dispute. The first thing to understand is why it’s undefined behavior to dereference a null pointer. In C++03, there’s actually a … Read more

Why does integer overflow on x86 with GCC cause an infinite loop?

When the standard says it’s undefined behavior, it means it. Anything can happen. “Anything” includes “usually integers wrap around, but on occasion weird stuff happens”. Yes, on x86 CPUs, integers usually wrap the way you expect. This is one of those exceptions. The compiler assumes you won’t cause undefined behavior, and optimizes away the loop … Read more