Why does the following code outputs 22: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Why does the following code outputs 22:

#include <iostream> using namespace std; int main() { int x=3; if(x=2){ cout << 2; } else { cout << 3; } cout << x; return 0; }

27th Jan 2017, 7:14 PM
Emanuel Dajti
Emanuel Dajti - avatar
2 Answers
+ 7
My best guess is: because it is x = 2, it assigns x to 2, then it is automatically true therefore outputting a 2 as you told it; cout << 2; when the program exits the if statement, x is set to 2, so it prints 2, resulting in 22. If you added an endl; it would be 2 2.
27th Jan 2017, 7:38 PM
Dawzy
Dawzy - avatar
+ 3
@ルカ he is asking why it outputs 22, not why it is'nt working, which in this case, there is no errors
27th Jan 2017, 7:42 PM
Dawzy
Dawzy - avatar