Obscure C code (was Re: Excessive optimization)
eric at brouhaha.com
Thu Dec 2 18:24:43 CST 2010
Fred Cisin wrote:
> Of course your example would work.
> I'm assuming that it was created by mistake, not a deliberate attempt to
> print 14 characters from pseudo-random places in memory.
> When you shoot yourself in the foot, C has no "gun-control".
> What would an excessive optimization compiler change it to?
By definition, if it is "excessive" optimization, it might do anything!
> A[i++] = i++;
> Many people think that they know what that will do. They may even be
> right for THEIR compiler, but I don't think that even ANSI C is a rigid
> enough specification to pin down the sequence of certain actions.
I can't quote chapter and verse, but I'm fairly sure the standard will
say that the result of that assignment is undefined.
In pre-standard C, it is also undefined, but for a different reason.
Many programmers would say "I would never write code like that", but
I've seen statements like that creep into code as a result of
cut-and-paste or global-search-and-replace operations that weren't
carefully checked. It's also quite possible when writing complex
expressions to come up with things like that which are not necessarily
obvious to casual inspection. It is good that many compilers will
detect these things and generate warnings. When I have the power to do
so, I generally treat warnings from the compiler as fatal errors
requiring a fix, and not acceptable in released code.
More information about the cctech