#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a=1;
printf("%d\t%d\t%d\n",a,++a,a++);
return 0;
}
Why the output of the code is 3 3 1
. someone explain me how this kind of output happen?
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a=1;
printf("%d\t%d\t%d\n",a,++a,a++);
return 0;
}
Why the output of the code is 3 3 1
. someone explain me how this kind of output happen?
Seems like your compiler reads the parameters from right to left
printf("%d\t%d\t%d\n",a,++a,a++); // a = 1
a++ returns a and increments it by 1
printf("%d\t%d\t%d\n",a,++a, 1); // a = 2
++a increments a by 1 and returns the result
printf("%d\t%d\t%d\n",a, 3, 1); // a = 3
a is just a
printf("%d\t%d\t%d\n", 3, 3, 1); // a = 3
But AFAIK this is kinda UB because the c++ standard doesnt rule in which order the parameters are read, so I wouldnt bet on it beeing the same on different compilers
Edit: With C++17 its no longer UB but unspecified. You should still avoid it
This is undefined behaviour as per the order of evaluation. reference (see chapter Undefined behavior)
The output is:
3 3 1
because it evaluates as follows:
a++
use a(1) and a becomes 2
++a
a becomes 3 and use a(3)
use a(3)
Important is to know that a++
is post-increment and ++a
is pre-increment.
Post-increment means: use the value and increase it after.
Pre-increment means: increment the value and use the incremented value.