Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top