C++ Switch Statements | Find output programs | Set 1

This section contains the C++ find output programs with their explanations on switch statements (set 1).
Submitted by Nidhi, on June 02, 2020

Program 1:

#include <iostream>
using namespace std;

int main()
{
    switch (printf("Hello World")) {
    case 0x09:
        cout << " India";
        break;

    case 0x0A:
        cout << " Australia";
        break;

    case 0x0B:
        cout << " USA";
        break;

    case 0x0C:
        cout << " England";
        break;
    }
    return 0;
}

Output:

Hello World USA

Explanation:

The above code will print "Hello World USA" on the console screen.

As we know that printf() function prints data on the console screen and returns the total number of characters printed on the screen.

printf("Hello World")

The above printf() function returns 11. And the hexadecimal equivalent of 11 is 0x0B, then case 0x0B will be executed.

And the final output is "Hello World USA".

Program 2:

#include <iostream>
using namespace std;

int main()
{
    int A = 10, B = 5, C = 2;

    switch (A * ++B + C - 8) {
    default:
        cout << "Pakistan ";
    case 0x09:
        cout << "India ";
        break;
    case 0x0A:
        cout << "Australia ";
        break;
    case 0x0B:
        cout << "USA ";
        break;
    case 0x0C:
        cout << "England ";
        break;
    }

    return 0;
}

Output:

Pakistan India

Explanation:

The above code will print "Pakistan India " on the console screen. Here we pass an expression in the switch block. Based on the expression result, the case will be executed. 

Evaluate the expression step by step:

int A=10,B=5,C=2;
	
=A*++B+C-8
=10*6+2-8
=60+2-8
=54

The result of the expression is 54 and there is no such case is defined. Thus, the default case will be executed and then the case 0x09 will be executed (Because break statement is missing after in default case)

Then the final output "Pakistan India" will be printed on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.