I wrote a delay loop. One hundred million iterations of nothing, which is a thing C is supposed to allow you to write. At -O0 it existed. At -O2 it did not exist. The compiler looked at my loop, decided nothing inside it mattered, and deleted the entire concept of it.
volatile uint32_t sink;
for (uint32_t i = 0; i < 100000000u; i++) {
sink = i; /* the optimizer cannot remove this */
}
The manual was very calm about it. The behavior is undefined, which does not mean the program crashes. It means the program is excused. The compiler may do anything, and the anything it chose was to edit me.
Volatile
The fix is one word. Volatile. You tell the compiler that this memory has a life outside its understanding, a side gig, friends it has not met. Then the loop is allowed to exist. I think about that word a lot. Volatile. It means I might change and you cannot assume otherwise. It is the only honest word in the language.
Somewhere in this I diffed two builds of the same program, a week apart, between which I had actually changed the source, and the binaries were identical. The change was real, I had the diff, the diff compiled, and the output did not move. I rebuilt both from clean trees and got the same two identical binaries, which is impossible, which I measured twice, which I am reporting in one sentence and then leaving alone.
Undefined behavior does not mean the machine misbehaves. It means you are no longer entitled to an explanation.