Prefix and postfix | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Prefix and postfix

Guys!! I have crazy thing project that make my brain burn. int a = 100; int b = a++; int c = ++a; Cout << a << b << c <<endl; Output: 102 100 102 -.-.-.-.-.-.-.-. Why is that? Why output a = 102 not 100? Please please please T-T

11th Sep 2022, 3:27 AM
Nett
Nett - avatar
4 Answers
+ 3
E ~ J thank you so much 😁😁
11th Sep 2022, 4:53 AM
Nett
Nett - avatar
+ 2
E ~ J that’s mean “ a “ working from the top to bottom?
11th Sep 2022, 4:20 AM
Nett
Nett - avatar
+ 2
It's simple look Lets define: int c = 5; Now when you use the operator ++ you must understand 2 things: 1.- When operator ++ it's before var its mean: *First increment then use* so: if we say int d = ++c; d = 6 because first increment c and then assing it to d. Here: c == 6 and d == 6 2.- Now, when operator ++ it's after var its mean: *First use then increment* so: if we say int z = c++; z = 6 because we assing the current value of c to z and then we increase c At this point: d == 6, z == 6, c == 7 I hope it helps. Cheers
13th Sep 2022, 12:08 AM
Null
Null - avatar
+ 1
Nett you are compounding the value of a. try this instead. int a = 100; cout<<a<<endl; int b = a++; cout<<b<<endl; //reset a a = 100; int c = ++a; cout<< c <<endl;
12th Sep 2022, 11:29 PM
Bob_Li
Bob_Li - avatar