+ 1

How is this right?

So I started learning C++, after the basics I got a quiz. It had a code: { int a=3; int b=2; b=a++; cout<<++b; } The right answear was 4. I don’t understand how. C++ shell told me: “cout was not declared in this scope” Basically it wasn’t right. Can you please explain it to me?

30th Jan 2018, 11:32 AM
Krisztiån Måté Cserge
Krisztiån Måté Cserge - avatar
4 Answers
+ 4
If the C++ told you that cout was not declared in this scope, it was because the code snippet you posted did not include the header <iostream>. This header is used for input and output, and without it; it will not recognize cout as a function. The answer was 4 because a = 3, and b = 3. Then b was reassigned to equal a++. So, b= a++. This means b = a = a + 1 (I know, it's weird). Then, it is printed as ++b, and this means 1 + b = b. It is assigned the value 4, before being printed. So, it prints 4. I hope I helped at least a little. 😂 It is kinda hard to describe.
30th Jan 2018, 12:12 PM
Dread
Dread - avatar
+ 7
first assign values for a and b. then reassign b value to be a++, which means increase a value by one (3+1=4) then assign it to b. cout<<++b; means type on the screen the actual value of b (which is 4); then increase its value by one (4+1=5). if you want to be more sure add a new line: cout<<b; (👈this will type 5 on the screen now).
30th Jan 2018, 12:14 PM
Mazin Ayash
Mazin Ayash - avatar
+ 2
Well yea, you could help me now I understand what kind of mistake I did. Thank you sir
30th Jan 2018, 12:14 PM
Krisztiån Måté Cserge
Krisztiån Måté Cserge - avatar
+ 1
You can check out the comment section in the quiz. There are quite a number of answers. Basically, a++ is a post-increment operator (executed after the statement) while ++b is a pre-increment operator (executed before the statement). For more information, read these: http://www.tutorialspoint.com/cplusplus/cpp_increment_decrement_operators.htm http://en.cppreference.com/w/cpp/language/operator_incdec Here is the equivalent code in case you don't understand the explanatons: #include <iostream> uisng namespace std; int main() { int a = 3; int b = 2; // replace b=a++; b=a; a+=1; // replace cout<<++b; b+=1; cout<<b; return 0; }
30th Jan 2018, 4:18 PM
Hanz
Hanz - avatar