On 5/5/2010 6:05 AM, aleksa wrote:
> Suppose I'm given a ptr to RECT and am modifying the RECT in a loop:
>
> V1:
>
> void ModifyRect (RECT* prect);
Assuming RECT is suitably declared, this is a valid declaration
for a function. It is not, however, a valid beginning for a function
definition. Two thoughts: Lose the semicolon, and make a habit of
posting real code rather than messed-up paraphrases.
> {
> while (cond) {
> if (newleft< prect->left) prect->left = newleft;
> .
> .
> .
> }
> }
>
>
> V2:
>
> void ModifyRect (RECT* prect);
Well, at least you're consistent.
> {
> RECT rect;
>
> while (cond) {
> if (newleft< rect.left) rect.left = newleft;
> .
> .
> .
> }
>
> *prect = rect;
> }
>
> (newleft is read sequentially from somewhere)
>
> Compiler generated code for V1 accesses memory all the time,
> while V2 holds everything in registers and only updates
> the prect when finished.
>
> I don't see a reason why both versions aren't coded the same.
> (there is no VOLATILE anywhere...)
>
> Just wondering, is this compiler specific or a C rule?
Most likely, the difference is that in V2 the compiler knows
that `rect' is distinct from all other variables in the program.
In V1, `prect' might be pointing pretty much anywhere, including
at something that overlaps `newleft' or some other variable. The
"C rule" would be that if you store a new value in something via
a pointer and then access that something by name, the access by
name and the access by pointer must agree on what's there.
You're on a game show, with three other people hidden behind
three doors. You know that Alice has ten dollars, Betty has twelve,
and Carol has eight, but you don't know who's behind which door.
The game show host pushes a dollar bill through the slot of Door
Number Two (access via pointer). How much money does Carol have?
To find out, you must ask her (access via name).
--
Eric Sosman
lid