Skip to content
Related Articles

Related Articles

Output of C++ programs | Set 37
  • Difficulty Level : Basic
  • Last Updated : 21 Aug, 2017

Predict the output for the following C++ code:

Question 1




#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






#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




#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




#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




#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>>”hello” 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.

This article is contributed by Palak Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :