3 ms·
> So most of the time the compiler sees const, it has to assume that someone, somewhere could cast it away, which means the compiler can’t use it for optimisati
by badsectoracula 7y ago
> So most of the time the compiler sees const, it has to assume that someone, somewhere could cast it away, which means the compiler can’t use it for optimisation. This is true in practice because enough real-world C code has “I know what I’m doing” casting away of const.
Some years ago i'd agree, but experience has shown that C/C++ compiler writers would rather win benchmark games than keep working code working. So it'd be nice if there was a better reason than "well, a lot of code would break if they did that".
- aflag 7y agoI think the point is that correct code could break.
- mafuyu 7y agoThat's typically in the case of UB, where compilers can make whatever assumptions they want. In this case, even if the code is completely within the C spec, the compiler cannot guarantee that the data is unmodified.
- BeeOnRope 7y agoIt's not even that: it's that if it sees a pointer declared const, it doesn't know if it was actually defined const. I may have a non-const object that I pass to a function that takes it by const pointer: that doesn't magically make it const! The object can still be modified, e.g., by an opaque function in the caller which modifies the object not necessarily by casting away cost, but because the object isn't const at all (e.g., it may have a non-const reference to the object). Const definitely helps optimizations, but only when the object is actually cost. References or pointers to const objects can't tell you that.