0

I've seen an interesting statement today with post-increment and pre-increment. Please consider the following program-

#include <stdio.h>

int main(){
    int x, z;

    x = 5;
    z = x++ - 5; // increase the value of x after the statement completed.
    printf("%d\n", z); // So the value here is 0. Simple.

    x = 5;
    z = 5 - ++x; // increase the value of x before the statement completed.
    printf("%d\n", z); // So the value is -1.

    // But, for these lines below..

    x = 5;
    z = x++ - ++x; // **The interesting statement
    printf("%d\n", z); // It prints 0

    return 0;
}

What's going on there actually in that interesting statement? The post-increment is supposed to increase the value of x after the statement completed. Then the value of first x is remain 5 for that statement. And in case of pre-increment, the value of second x should be 6 or 7 (not sure).

Why does it gives a value of 0 to z? Was it 5 - 5 or 6 - 6? Please explain.

aniskhan001
  • 7,981
  • 8
  • 36
  • 57

1 Answers1

10

It's Undefined Behavior. The compiler is free to do whatever it wants -- it may give 0, it may give 42, it may erase your hard drive, or it may cause demons to fly out of your nose. All of those behaviors are permitted by the C and C++ language standards.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 7
    Actually section `14.2.7` explicitly forbids the compiler from generating code that produces nose demons, all other behaviours are permitted though. – Paul Aug 27 '13 at 19:32
  • What is undefined is the statement ? Java wouldn't hesitate a minute ;) – Julien Aug 27 '13 at 19:32
  • Ok so it's undefined behaviour. But why? I would think it to evaluate as 5 - 6 (++x goes before the subtraction, x++ after it). Would changing it into (x++)-(++x) change the outcome? – Kevin Aug 27 '13 at 19:37
  • 2
    @Kevin No, there is still no sequence point. There is no rule as to whether the left operand or the right operand of `-` gets evaluated first. – Paul Aug 27 '13 at 19:37
  • @Paulpro But the unspecified order in which the operands may be evaluated is not what leads to undefined behaviour. – juanchopanza Aug 27 '13 at 19:44
  • @juanchopanza Sure it is. If there was a specified order than `-` would have to be a sequence point, and it would be well defined as `5 - 7` (or `6 - 6` if the right operand was chosen as the sequence point). Since there is no sequence point it is completely undefined behaviour. – Paul Aug 27 '13 at 19:47
  • 1
    @Paulpro If you overload pre/post increment, the evaluation order is still unspecified while the behaviour becomes well defined. – jrok Aug 27 '13 at 19:50
  • @jrok That's because you've added two sequence points. You'll end up with just unspecified behaviour rather than undefined behaviour. – Paul Aug 27 '13 at 20:03
  • @Paulpro that was my point. – juanchopanza Aug 27 '13 at 20:07