Sujet : Re: So You Think You Can Const?
De : ben (at) *nospam* bsb.me.uk (Ben Bacarisse)
Groupes : comp.lang.cDate : 09. Jan 2025, 01:49:05
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <87wmf44xry.fsf@bsb.me.uk>
References : 1 2 3 4 5
User-Agent : Gnus/5.13 (Gnus v5.13)
Tim Rentsch <
tr.17687@z991.linuxsc.com> writes:
Ben Bacarisse <ben@bsb.me.uk> writes:
... Modifying an object whose type is const qualified
is undefined, even if the object is in writable storage. A compiler
may assume that such an object has not changed because in a program
that has undefined behaviour, all bets are off. [...]
>
We need to be careful about what is being asserted here. There
are cases where a compiler may not assume that a const object
has not changed, despite the rule that assigning to a const
object is undefined behavior:
>
#include <stdio.h>
typedef union { const int foo; int bas; } Foobas;
>
int
main(){
Foobas fb = { 0 };
>
printf( " fb.foo is %d\n", fb.foo );
fb.bas = 7;
printf( " fb.foo is %d\n", fb.foo );
return 0;
}
>
The object fb.foo is indeed a const object, but an access of
fb.foo must not assume that it retains its original value after
the assignment to fb.bas.
Yes, good point. There is also the case of
volatile const int x;
which the compiler can't assume won't change even though the program
can't change it directly.
-- Ben.