Output of C++ programs | Set 37

Last Updated : 10 Feb, 2023
Predict the output for the following C++ code: Question 1 CPP
#include <iostream>
int main()
{
    if (std::cout << "hello")
        std::cout << " world";
    else
        std::cout << " else part";

    return 0;
}
Output: hello world Description: Since std::cout<<"hello" returns a reference to std::cout, therefore, the condition gets true, and the if block is executed.   Question 2 CPP
#include <iostream>
int main()
{
    if (2)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}
Output: hello Description: Since 2 is a non-zero(i.e., true), therefore, the conditions gets true and the if block is executed.   Question 3 CPP
#include <iostream>
int main()
{
    if (0)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}
Output: world Description: Since 0 is an equivalent of false(in this problem), therefore the conditions gets false and the else block is executed.   Question 4 CPP
#include <iostream>
int main()
{
    if (NULL)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}
Output: world Description: Since NULL is an equivalent of 0 i.e., false(in this particular problem), therefore the conditions gets false and the else block is executed.   Question 5 CPP
#include <iostream>
int main()
{
    int n;

    if (std::cin >> n) {
        std::cout << "hello";
    } else
        std::cout << "world";
    return 0;
}
Input: 100 Output: hello Description: Since std::cin>>100 returns a reference to std::cin, therefore, the condition gets true, and the if block is executed. Input: [nothing] Output: world Description: Since the input is not provided, the condition becomes false, and hence, the else block is executed.

Comment