+ 2
I do not get it...
If int a=3; int b=2; b=a++; cout<<++b; then WHY THE HELL the result IS EQUAL WITH 4 ??????
4 Answers
+ 16
int a = 3;
int b = 2;
// First, b = a, then a increment by 1
// b = 3, a = 3
b = a++;
// First, b increment by 1, then print out the b to the console
// b = 4, Output : 4
cout << ++b;
Important note:
120% avoid doing the incremental/decremental operation "in a row" inside the cout. That causes undefined behavior.
Example: Compare two groups together. They both do the same operation but as you clearly see, former expresion's behavior is completely undefiend.
#include <iostream>
using namespace std;
int main()
{
int x = 1;
int y = 2;
cout << x++ << " " << ++x << " " << --y << " " << y++ << "\n\n";
x = 1;
y = 2;
cout << x++ << endl;
cout << ++x << endl;
cout << --y << endl;
cout << y++ << endl;
}
Output:
2 3 2 2
1
3
1
1
Discussion : [https://stackoverflow.com/questions/33445796/increment-and-decrement-with-cout-in-c]
Live link : [http://cpp.sh/8xuaw]
+ 14
@Enurien it's work like this
int a=3 ; //a has assigned value 3 initially
int b=2; // b has assigned value 2 initially
b=a++; // a++ is post increment so first value is used then incremented so value 3 is assigned to b
b=3 now
cout<<++b; //this is pretty increment first value is incremented by 1 then store so b=4
and it will be print as output b=4
+ 1
b=a++ \\first it will assign the value of 'a' to 'b' and then add up 'a+1'.
so b=3 and a=4
in 2nd case '++b' it will add up to 1 and then assign.
so 'cout<<++b' means 'b+1' and print it.