Hacker News new | ask | show | jobs
by caf 2499 days ago
Local constant stack values surely can be completely deterministically verified as such by the optimiser even without the `const` modifier.

Only if their address doesn't escape.

2 comments

By ‘constant stack value’, I was referring to ‘effectively constant’ stack values, i.e. ones who aren’t reassigned in the scope or passed by mutable reference (or indeed are but aren’t actually modified by those functions anyway if the compiler can prove it).

My phrasing was probably a bit ambiguous there.

The compiler will detect any attempt at taking the address of the variable (including fancy things like most inline assembly) and skip the optimization, marking it as requiring a memory location.

However, it can still cheat by rearranging the memory write or even letting linker initialize the address.

We are in violent agreement.

An explicitly const-qualified object instead can be replaced with its value even if its address has escaped.