Forum unknown
· Programming
#Trivia
5 messages in this thread
Logic dictates that the first answer should be i=2 and the other i=3 j=3.
But, in C, the answer is indeterminate. WHEN the store actually takes place
is not determined by the spec.
As a matter of fact, using the value and assigning to it in the same
expression is EXPLICITLY undefined according to K&R (somewhere; I lent my
copy). Woe to all who try to port such things!
How about:
extern int garbunga;
int garfunc(i) int i; {
i += 5;
return i;
}
void main() {
garbunga = 27;
garfunc(garbunga++);
printf("%d", garbunga);
}
What does this print, and what did garfunc return?
As a matter of fact, using the value and assigning to it in the same
expression is EXPLICITLY undefined according to K&R (somewhere; I lent my
copy). Woe to all who try to port such things!
How about:
extern int garbunga;
int garfunc(i) int i; {
i += 5;
return i;
}
void main() {
garbunga = 27;
garfunc(garbunga++);
printf("%d", garbunga);
}
What does this print, and what did garfunc return?
Well, I evaluated it based on operator precedence and associativity. In
K&R on page 50, it does in fact state that ++ and — operators can become
indetermined and they use the example a[i] = i++;
I also made the presumption that the compiler will "fetch" into a
register, increment and then store the register value back; therefore, leaving
the value unchanged (which is the answer I got with my compiler when I did try
it).
The same is true for Weird(), if the compiler designer used precedence
when the exact value may be indeterminate, the results will be i=3 and j=3
(again, the results I obtained).
But, yes, it is dependent on machine and compiler. \
Don
Well, I evaluated it based on operator precedence and associativity. In
K&R on page 50, it does in fact state that ++ and — operators can become
indetermined and they use the example a[i] = i++;
I also made the presumption that the compiler will "fetch" into a
register, increment and then store the register value back; therefore, leaving
the value unchanged (which is the answer I got with my compiler when I did try
it).
The same is true for Weird(), if the compiler designer used precedence
when the exact value may be indeterminate, the results will be i=3 and j=3
(again, the results I obtained).
But, yes, it is dependent on machine and compiler. \
Don