how to make gcc warn about arithmetic signed overflow
James K. Lowden
Mon Sep 23 15:47:00 GMT 2013
On Mon, 23 Sep 2013 08:54:57 +0100
Jonathan Wakely <email@example.com> wrote:
> > const_cast
> > will surely let you change the value of a const object without
> > treading into undefined behavior.
> No, it surely won't!
> If an object is defined as const in the first place then it is
> undefined behaviour to change it.
> And the definitive reference, 188.8.131.52 [dcl.type.cv]/4:
> "Except that any class member declared mutable (7.1.1) can be
> modified, any attempt to modify a const object during its lifetime
> (3.8) results in undefined behavior."
Oh, gee, someone is wrong on the Internet again. Thanks for the
As far as I can make out, the only remaining reliable use of const_cast
is to convert a type that was passed as a const reference back to
original (non-const) type, if such it was.
7.1.6 is itself mutable, it turns out. My yellowed ARM, copyright
1990, is considerably more relaxed on the question. (And considerably
easier to read. I don't know how anyone learns C++ these days, so
dense is the technical terminology.)
Stroustrup's commentary says, "adding const to a declaration ensures
that an object to which the const is applied cannot have its value
changed ... unless an explicit type conversion is used.... const does
not mean 'store in readonly memory' nor does it mean 'compile time
Regarding errors, it mentions only that a const object might wind up in
"readonly" memory, in which case attempts to modify it will result in a
runtime error: "The effect of a write operation on any part of [a
const] object is either an addressing exception or the same as if the
object had been non-const". That is, either it works or you get an
exception from the hardware, depending on whether the computer can
execute the code.
Notably missing from that description is the possibility that the
compiler can do anything it wants because the programmer colored
outside the lines. The purpose of const was to aid the programmer in
preventing accidental changes to a variable. Because compiler writers
care more for efficiency than convenience, it's slowly metastasizing
into a no man's land between programmer and machine.
More information about the Gcc-help