4 ms·
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 op
by giomasce 5y ago
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 https://godbolt.org/z/KWrW45rK8
- not2b 5y agoThis 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).
- toast0 5y ago> (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?
- deleted 5y ago[deleted]
- why_only_15 5y agoInterestingly GCC will still optimize the loop function even if you have code that modifies the modulus. https://godbolt.org/z/EE9PnrY7s https://godbolt.org/z/EE9PnrY7s
- colonwqbang 5y agoThat code is invalid, it would give a compiler warning and possibly a runtime exception.
- Snoonan999 5y agoConst is to state that this module is not allowed to modify. Think on what'const volatile int foo' means. Mostly seen in embedded space.