What is the output of the following snippet? #include <iostream> using namespace std; int main(){ int i = 1; if (--i == 1) { cout << i; } else { cout << --i; } return 0; } 1 --1 -1 0
Question
What is the output of the following snippet?
#include <iostream> using namespace std;
int main(){ int i = 1; if (--i == 1) { cout << i; } else { cout << --i; } return 0; }
1
--1
-1
0
Solution
The output of the given code snippet will be -1.
Here's the step by step explanation:
-
The variable
iis initialized with the value 1. -
In the
ifcondition,--iis used which is a pre-decrement operation. This means that the value ofiis decremented by 1 before the comparison. So,ibecomes 0. -
The
ifcondition checks ifiis equal to 1. Sinceiis 0, the condition is false. Therefore, the program goes to theelseblock. -
In the
elseblock,cout << --i;is executed. Again,--iis a pre-decrement operation. So,iis decremented by 1 again and becomes -1. -
The value of
i(-1) is printed.
So, the output is -1.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following PHP code?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.