0
#include <stdio.h>

int main() {
    int x, y, z;
    printf("Enter x and y: ");
    scanf("%d%d", &x, &y);
    z = x++ + --y + (x<y);
    printf("z = %d\n", z);
    return 0;
}

For x = 1, y = 3, I'm getting z = 3 instead of 4, is this compiler related or am I wrong?

z = 1++ + --3 + (1<3); z = 1 + 2 + (1<2); z = 3 + 1 = 4

an9xia
  • 19
  • 6
  • Note - the undefinedness here is because you are updating `x` and `y` (`x++`, `--y`) *and* using them to compute a result (`x < y`) without an intervening sequence point. – John Bode Nov 12 '20 at 20:57
  • @JohnBode z = 1++ + --3 + (1<3); z = 1 + 2 + (1<2); z = 3 + 1 = 4, what do you mean by that? – an9xia Nov 12 '20 at 21:01
  • it doesn't matter what the values of the variables are - if you try to update a variable using `++` or `--` *and* use it to compute a value without an intervening sequence point, then the behavior is undefined and the result is not predictable, nor is it guaranteed to be consistent. You'll have to compute `x < y` in a separate statement, save the result to another variable, and then add that to `z`. – John Bode Nov 12 '20 at 21:06
  • @an9xia: How do you know that `x++ + --y + (x – Eric Postpischil Nov 12 '20 at 21:09
  • @EricPostpischil thank you so much, this answered my question. :) – an9xia Nov 12 '20 at 21:20
  • @an9xia: Yeah, there's no well-defined result. C does not force left-to-right evaluation, and it doesn't force `x++` or `--y` to be updated *immediately* after evaluation. You can't assume that `x` in `x < y` is the value of `x` before or after the `++` operation. The C language definition *specifically* calls this sort of thing out as "undefined behavior", meaning neither the compiler nor runtime environment are required to handle it in any particular way. There's no guarantee that the result will be predictable or repeatable. – John Bode Nov 12 '20 at 21:25

0 Answers0