Knowee
Questions
Features
Study Tools

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

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the given code snippet will be -1.

Here's the step by step explanation:

  1. The variable i is initialized with the value 1.

  2. In the if condition, --i is used which is a pre-decrement operation. This means that the value of i is decremented by 1 before the comparison. So, i becomes 0.

  3. The if condition checks if i is equal to 1. Since i is 0, the condition is false. Therefore, the program goes to the else block.

  4. In the else block, cout << --i; is executed. Again, --i is a pre-decrement operation. So, i is decremented by 1 again and becomes -1.

  5. The value of i (-1) is printed.

So, the output is -1.

This problem has been solved

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?

1/4

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.