Hi!

Karen Shaeffer wrote:
I see your point. My sticking point is that the process is actually
running on a physical machine. And the addresses, although virtual,
do translate to a unique physical memory location. And, the value
stored in that location cannot be 0 and 5 at the same time. And my
comments were addressing that the undefined behavior of this illegal
assignment should not violate the physical constraints of what is
actually stored in that physical address.

Correct, and there aren't two values in that physical memory
location, there is only one value stored in there: the value 5.
(Assuming GCC 4.1.2 with -O2.)  At the time where the first
printf() is executed, the program won't even bother to go read
that memory location (which contains the value 5), because it
*knows* that it contains the value 0.  It knows it because you
promised that it contains the value 0 and that it will never ever
change.  So it won't even bother loading it and directly print the
value 0.  That's the result of an optimization: Not reading a
memory location when its content is already known makes your
program run faster; just use the known content instead.  But you
as the programmer have given GCC a promise that you broke later on
and thus the program behaves in an arguably unexpected way.  (It
*is* expected, since printing what it prints falls under the
definition of "undefined behavior.)

In fact, that memory location is never actually read.  When
printing *cip and *ip, the program simply prints 5, because it
knows there's the value 5 in that memory location, because it just
wrote it there.  Even the "ci = 0" is not storing to any memory
location, it has been optimized away.  All that remains is a
useless assignment of the value 5 into a memory location that is
never read again, and the resulting code:

   printf("const int ic = %d   *cip = %d   *ip = %d\n", 0, 5, 5);

However, if I compile with -O0 (no optimization), then the program
prints what you might have expected.

"Undefined behavior" means for you: Avoid it and don't expect the
compiler to try to do any sane thing when encountered or to reduce
damage to a minimum or to do the "expected" thing.  That would
even be impossible to do.  Just don't be undefined and you're
fine.

Oh, and looking at the assembly output (with "gcc file.c -S") is
often very helpful to see what's going on.

Hope this helps,
jlh

Reply via email to