This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: how to make gcc warn about arithmetic signed overflow


On 23 September 2013 05:03, James K. Lowden wrote:
> On Sat, 21 Sep 2013 19:30:02 +0100
> Jonathan Wakely <jwakely.gcc@gmail.com> wrote:
>
>> > its value can be changed using pointers
>>
>> No, that's not true. You can't change the value of a const object in a
>> valid program.
>
> I don't know if we're talking C or C++ at this point, but 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.

1.9 [intro.execution]/4:
"Certain other operations are described in this International Standard
as undefined (for example, the effect of attempting to modify a const
object)."

5.2.11 [expr.const.cast]/7:
"[ Note: Depending on the type of the object, a write operation
through the pointer, lvalue or pointer
to data member resulting from a const_cast that casts away a
const-qualifier may produce undefined
behavior (7.1.6.1). — end note ]"

And the definitive reference, 7.1.6.1 [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."

You can't even do it by destroying an a const objehct and recreating a
new object at the same address:

3.8 [basic.life]/9
"Creating a new object at the storage location that a const object
with static, thread, or automatic storage duration occupies or, at the
storage location that such a const object used to occupy before its
lifetime ended results in undefined behavior."


> Regarding the OP's query
>
>> > int r = ab * bc;
>
> although the provided example is simple enough, it's the compiler's
> job is to generate object code, not to do static analysis.
>
> Even if the values are const, in the general case they could be
> modified by another module or another thread.  The compiler simply
> doesn't have enough information to warn of every runtime overflow.

Unless they're automatic variables and the compiler can determine
their addresses haven't been taken or haven't escaped the current
scope. Escape analysis should be able to do that, ideally.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]