Search code examples
cundefined-behaviorpost-incrementpre-increment

Pre Increment & Post Increment


Today I revisited Pre Increment and Post Increment.

Basic definitions I know.

Pre Increment - Increments the Value and returns the value.

Post Increment - Increments the Value and returns the value prior to increment.

But Doing some combinations of them i am stumped.

Using a basic C program, here is what I tested.

With i =0 initially.

1st Test

printf("%d %d",++i,++i);

Ouput:

2 2

I Expected:

1 2

2nd Test

printf("%d %d",i++,i++);

Ouput:

1 0

I Expected:

0 1

3rd Test

printf("%d %d",i++,++i);

Ouput:

1 2

I Expected:

0 2

4th Test

printf("%d %d",++i,i++);

Ouput:

2 0

I Expected:

1 1

I figured the evaluation might be from the right side or the left side. Maybe from left in case of Pre Increment & Right in case of Post increment. Maybe Pre Increment had a higher priority than Post increment. Some ideas to match the results, but assumption made on one test doesn't explain the other output.


Solution

  • Everything you have is undefined behavior because you are modifying the same variable multiple times between the same pair of sequence points. For example

    i = i++;
    

    is undefined as well. There's a deeper discussion here, and there's a nice slideshare that covers this and more "deep C" quirks.

    The other issue is the order of evaluation. The arguments are evaluated in an unspecified order, so if you have

    f(a(), b(), c());
    

    it can call a, b, and c in any order.

    You're mixing undefined behavior and unspecified behavior, so although you could venture a guess to explain why you get the output you do, it's hard to give a satisfactory explanation since it's so random.