0

While starting out with C, I learned about the post-increment and pre-increment operators. I understood the basic difference between the two as follows:

"The pre-increment operator (++i) would increment the value and return it in an expression with the 'side-effect' of making the value of i increase by 1. The post-increment(i++) operator on the other hand would first return the value of i in the expression and THEN increment the value of i by 1."

Here's what I wanted to know:

While trying out related programs i stumbled upon;

#include<stdio.h>

int main()
{
   int a=10;
   printf("a=%d, a++=%d, ++a=%d",a,a++,++a);
}

The output of the above code is:

a=12, a++=11, ++a=12

The way I interpreted it is that ++a would increment the value but return it only after the ENTIRE expression has been evaluated.

So the printf statement starts executing, it starts with ++a, since here it is used as a statement rather than an expression, it just increments a to 11. But does not print it, the program moves to a++, which returns 11 first passing it onto the format string, then the value of a is further incremented to 12 which is (somehow) returned to ++a and a both.

TL;DR : a,++a print the final value after all the changes, a++ prints current value.

But this seems to raise more question than it answers, e.g.

  1. How does the printf statement 'jump back' to ++a after the statement is over or does a++ temporarily store the incremented value somewhere else and only return it after the entire statement is executed?

  2. In general how can we predict the behavior of an operation whether it will immediately give back the value or return it after all is over?

Modifying the code a little bit:

#include<stdio.h>

int main()
{
   int a=10,b,c;
   printf("a=%d, b=%d, c=%d",a,b,c);
}

The output of the above code is:

a=12, b=11, c=11

I have no idea how this is to be interpreted.

  • https://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c – Mat Dec 18 '21 at 08:31
  • "In general how can we predict the behavior of an operation whether it will immediately give back the value or return it after all is over?" We just don't write code where it matters. The "all is over" happens faster is short expressions with more semicolons. – BoP Dec 18 '21 at 10:22

0 Answers0