Let's trace through the code.
Example 1:
main()
This is no longer correct (since 1999). main
needs a return type: int main()
.
{
int x=4,y,z;
Here x = 4
whereas y
and z
are indeterminate.
y=--x;
--x
decrements x
(from 4
to 3
) and returns the new value of x
(3
), which is then assigned to y
. At the end we have x = 3
, y = 3
, and z
still indeterminate.
z=x--;
x--
decrements x
(from 3
to 2
) and returns the old value of x
(3
), which is then assigned to z
. At the end we have x = 2
, y = 3
, z = 3
.
printf("\n%d %d %d",x,y,z);
Here we're calling printf
, but the function is not declared. The code is missing #include <stdio.h>
; without it, the behavior is undefined (because it's calling an undeclared varargs function). But let's assume <stdio.h>
was included. Then:
This outputs x
, y
, z
as 2 3 3
. Note that the format string should be "%d %d %d\n"
; in the C model, lines are terminated by '\n'
, so you should always have a '\n'
at the end.
}
Example 2:
main()
Same issue, should be int main()
and #include <stdio.h>
is missing.
{
int k=35;
Now k = 35
.
printf("\n%d %d %d",k==35,k=50,k>40);
This is just broken. Function arguments can be evaluated in any order. In particular, the assignment to k
(k = 50
) and the comparisons (k == 35
, k > 40
) are not sequenced relative to each other, which means this piece of code has undefined behavior. You're not allowed to modify a variable while at the same time reading from it.
}
People answer this is undefined behaviour, but if this is asked in interviews, how should one answer them?
Tell them "this is undefined behavior". That's the correct answer. The example above is not required to produce any output. It could print 1 2 3
, but it also could print hello!
, or go into an infinite loop, or crash, or delete all of your files.
As far as the C standard is concerned, the code is simply meaningless.
(What happens on any particular platform is highly dependent on your compiler, the exact version of the compiler, any optimization options used, etc.)