Top "Undefined-behavior" questions

The unpredictable outcome of compiling or executing a program which breaks rules of the language neither compiler, interpreter nor runtime-system have to enforce.

Why isn't arr[-2] equivalent to -2[arr]?

#include <iostream> using namespace std; int main() { int arr[3] = { 10, 20, 30 }; cout << arr[-2] << endl; cout &…

c++ arrays undefined-behavior
What's a proper way of type-punning a float to an int and vice-versa?

The code below performs a fast inverse square root operation by some bit hacks. The algorithm was probably developed by …

c++ undefined-behavior gcc-warning strict-aliasing type-punning
When is casting between pointer types not undefined behavior in C?

As a newcomer to C, I'm confused about when casting a pointer is actually OK. As I understand, you can …

c casting undefined-behavior
Is it legal for source code containing undefined behavior to crash the compiler?

Let's say I go to compile some poorly-written C++ source code that invokes undefined behavior, and therefore (as they say) "…

c++ language-lawyer undefined-behavior
Why is a = (a+b) - (b=a) a bad choice for swapping two integers?

I stumbled into this code for swapping two integers without using a temporary variable or the use of bitwise operators. …

c++ c swap undefined-behavior sequence-points
A C++ implementation that detects undefined behavior?

A huge number of operations in C++ result in undefined behavior, where the spec is completely mute about what the …

c++ undefined-behavior
Does "Undefined Behavior" really permit *anything* to happen?

EDIT: This question was not intended as a forum for discussion about the (de)merits of undefined behavior, but that's …

c++ c language-lawyer undefined-behavior
Is right shift undefined behavior if the count is larger than the width of the type?

I just checked the C++ standard. It seems the following code should NOT be undefined behavior: unsigned int val = 0x0…

c++ gcc assembly standards undefined-behavior
Is passing a C++ object into its own constructor legal?

I am surprised to accidentally discover that the following works: #include <iostream> int main(int argc, char** argv) { …

c++ class constructor language-lawyer undefined-behavior
Why does printf("%f",0); give undefined behavior?

The statement printf("%f\n",0.0f); prints 0. However, the statement printf("%f\n",0); prints random values. I realize I'm exhibiting …

c++ c printf implicit-conversion undefined-behavior