const + optimizations [WAS: Need C optimization help]

Ian Lance Taylor iant@google.com
Fri Aug 13 18:23:00 GMT 2010


Enrico Weigelt <weigelt@metux.de> writes:

> * Segher Boessenkool <segher@kernel.crashing.org> wrote:
>  
>> Modifying an object via a const lvalue is a constraint violation; any
>> program that does this is not a valid C program.
>
> Is the compiler able to use that for optimizations (eg. hold
> const variables in registers, etc) ?

It depends.  Modifying an object via a const lvalue is invalid, but it
is possible for the object to be modified in other ways.  E.g., a const
char* pointer may point to a value which is modified via a normal char*
pointer.  An object which is itself declared const may not be modified
in any way, and the compiler does take advantage of that.

>> Modifying a const object via a non-const lvalue is undefined behaviour.
>
> Is there a flag to forbid that ?

-Wcast-qual -Werror.

Ian



More information about the Gcc-help mailing list