C
Chris Dollin
Naresh said:#include<stdio.h>
void main(void)
`main` should return `int`. The behaviour of your
code is undefined.
{
int k = 0;
k = k++;
printf("\n %d", k);
}
It gives me expected outcome as 1 on msvc 6 without any warnings or
errors. Then, why should we call it as undefined behaviour.
Because it /is/ undefined behaviour - the standard does not specify
any particular behaviour for this expression (`k = k++`). An implementation
may issue a warning, it may reject the code, it may print 17, it may
delete your files.
Isnt it ok
to consider it as two statements as
k = k + 1;
k = k;
It's also OK to consider it as the two statements:
k = -1;
k = -2;
Or as a double-effect machine instruction [1]
mov k k | add k k #1
which does both operations in parallel and, if it so happens that
the target register is the same in both instructions, fills it
with the bitwise OR of the results. This gets your expected result,
but for
int k = 1;
k = k++;
will put 3 into k.
Of course a later architecture, noting that allowing multiple
writes to the same register was silly and that no compiler
would generate it, arranged that such instructions were
co-processor invocations to co-processor `k`, and now your
program attempts to do an FFT where the `k #1` part of the
instructions specifies the array address and breaks because
the address is illegal.
BOOM tomorrow. There's always a BOOM tomorrow.
[1] For an architecture which I have made up, but which isn't
necessarily stupid.