Output of C++ programs | Set 37

Predict the output for the following C++ code:

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    if (std::cout << "hello")
        std::cout << " world";
    else
        std::cout << " else part";
  
    return 0;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    if (2)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    if (0)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    if (NULL)
        std::cout << "hello";
    else
        std::cout << "world";
    return 0;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    int n;
  
    if (std::cin >> n) {
        std::cout << "hello";
    } else
        std::cout << "world";
    return 0;
}

chevron_right


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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.