This is the mail archive of the gcc@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: Compiling GCC With a C++ Compiler (g++)


On Wed, 13 Oct 2004, Dave Korn wrote:

>   If you pass a pointer to a struct as an argument to a function, and there
> is a field in the struct that is declared const, the compiler is liable to
> assume that the value of that field cannot be modified by the called
> function and cache it in registers or stack slots across the function call,
> or perhaps make assumptions about known values in the field, that would
> become invalid if the callee casts away the constness and modifies the
> field.  

Wrong.  Even with "restrict" you can't make such assumptions in the caller 
unless you can see the definition of the function (whether the parameter 
is declared with "restrict" may differ between function declarations and 
the definition) and know that the function has no other access to that 
object (it might not use the restricted pointer argument at all, and 
access and modify the object through some other pointer it has access to).  
Without "restrict" the only relevant undefined behavior is if the object 
is *defined* with qualified type (6.7.3#5).  This can apply with static or 
automatic storage duration declarations such as

  struct { const char x } y = { z };

but cannot apply to an object of allocated storage duration.

> [*] Well, a variation of it: no struct involved, just a const variable.

If the variable is declared const

  const int y;

then indeed it can't be modified.  But if you do

  const int *y = malloc(sizeof(const int));

then you can modify *(int *)y.  (Strictly, the conversion from const int * 
to int * isn't guaranteed to preserve the value of the pointer, but as int 
* and const int * have the same representation and alignment requirements 
the called function could copy the value using memcpy.)

-- 
Joseph S. Myers               http://www.srcf.ucam.org/~jsm28/gcc/
    jsm@polyomino.org.uk (personal mail)
    joseph@codesourcery.com (CodeSourcery mail)
    jsm28@gcc.gnu.org (Bugzilla assignments and CCs)


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