Hacker News new | past | comments | ask | show | jobs | submit login

Are you sure? Isn't it UB to modify a const object? It will probably end up in a non-writable memory page.

EDIT: gcc seems to agree with me: you can see the optimized version here[1] and the unoptimzed version if you remove "const".

[1] https://godbolt.org/z/KWrW45rK8




This is why language standards specify what the compiler can assume and call out some behavior as undefined, exactly so compilers don't have to be paranoid and produce code that sucks. If an underlying object is const, the compiler is allowed to assume that it does not change (it is valid to cast away const on a pointer or reference, but not if the object itself was declared const).


> (it is valid to cast away const on a pointer or reference, but not if the object itself was declared const).

Isn't it valid to cast to non-const for a const, but only invalid to modify the const through the casted pointer?


Interestingly GCC will still optimize the loop function even if you have code that modifies the modulus. https://godbolt.org/z/EE9PnrY7s


That code is invalid, it would give a compiler warning and possibly a runtime exception.


Const is to state that this module is not allowed to modify. Think on what'const volatile int foo' means.

Mostly seen in embedded space.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: