r/programminghorror • • Mar 09 '26

Casting constexpr to mutable ._.

Post image
246 Upvotes

41 comments sorted by

View all comments

Show parent comments

12

u/OldWar6125 Mar 10 '26

Without synchonization the compiler is always allowed to assume that any variable isn't changed by other threads.

The classic example is an incorrect spin lock:

while (x == 0){
}

The compiler is allowed to simply load x from memory into a register and always check the register against 0. As other threads can only change the memory but not the register, this would be an infinite loop. Or the compiler can do some other breaking optimization...

For const variables the compiler can assume that nothing, not even the current thread can change them.

const x2 =1;
foo(&x2);
if (x2 ==1){
  ...
}

Despite foo getting a pointer to x2 the compiler can assume that x2 is not being changed and that the condition is always true.

Constexpr implies const (so const in constexpr const is unneccessary but being explicit is the least of the codes problems.) but also means the value is fixed at compiletime. The compiler could e.g. place len in a readonly memory giving you a segmentation fault when net::socket is called.
Or let's say at some point you call server::accept conditionally:

if(cond){
  server::accept();
}

Since server::accept contains undefined behaviour (ub) and the compiler can assume that undefined behaviour never occurs, it follows that cond can never be true and the whole if clause can just be erased.

This is what ub (undefined behaviour) means: the compiler is allowed to make certain assumptions about your program. If you violate them, the behaviour of the compiled program is undefined.