I came across this code:
#include<iostream>
using namespace std;
int main()
{
int a=5,
b=a++ - 2;
cout << b;
return 0;
}
The output is 3. Why is it not 4?
I came across this code:
#include<iostream>
using namespace std;
int main()
{
int a=5,
b=a++ - 2;
cout << b;
return 0;
}
The output is 3. Why is it not 4?
-2 or - 2 should not give any error see there are two types of operator post increment and pre increment a++ is post increment it means first it will assign the value then it will increase the value by 1
meaning b = 5 - 2; a will get get increased by 1 a=6 now but in the equation it will be 5
but if you do ++a
then it will first increase the value then assign meaning b = 6 - 2;
-2 or - 2 wont give any error
check here
Lets break it down step by step.
These type of comma separated expressions happen from left to right. So its the same as this,
int a = 5;
int b = a++ - 2;
In this, a++
increments the value of a
by one and then assigns it to it. Then the - 2
happens. Simply what happens under the hood is,
// Here 5 is the value of a.
int b = 5 - 2, a = a + 1;