Problem in Switch-Statement.

I am facing a little problem in switch-statement, as we can use integer in our switch statement than why second program is not working.

First Program:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
int main ()
{
	char grade;

	cout << "Please enter your grade\n";
	cin >> grade;

	switch (grade)
	{
	case 'A':
		cout << "Excellent\n";
		break;

	case 'B':
		cout << "Good\n";
		break;

	default:
		cout << "That is not a possible grade\n";
	}

	cout << "    \n";
	cout << "End of Program\n";


	return 0;

}


Second Program:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
int main ()
{
	int num_1;

	cout << "Please enter your Position in Class\n";
	cin >> num_1;

	switch (num_1)
	{
	case '1':
		cout << "Excellent\n";
		break;

	case '2':
		cout << "Good\n";
		break;

	default:
		cout << "That is not a possible grade\n";
	}

	cout << "    \n";
	cout << "End of Program\n";


	return 0;

}

Second program runs fine but when I enter input, it is just showing default case only why?
as we can use integer in our switch statement than why second program is not working.


Because num_1 is an integer and '1' and '2' are chars. They are not of the same type, so they will never be true. Read @dhayden's explanation

When they say you can use integers in your switch statements, they mean with integer cases too.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;
int main ()
{
	int num_1;

	cout << "Please enter your Position in Class\n";
	cin >> num_1;

	switch (num_1)
	{
	case 1: // not 1 and not '1'
		cout << "Excellent\n";
		break;

	case 2: // note 2 and not a '2'
		cout << "Good\n";
		break;

	default:
		cout << "That is not a possible grade\n";
	}

	cout << "    \n";
	cout << "End of Program\n";
      
	return 0;

}


http://www.cpp.sh/4xmd
Last edited on
Because num_1 is an integer and '1' and '2' are chars. They are not of the same type, so they will never be true.

The reason is a little different. '1' and '2' are the encodings for those characters (numbers 49 and 50 respectively if the computer uses ASCII encoding). So case '1' is like saying case 49 (except that one is an char and the other is an int.

The compiler can compare integers to chars just as it can compare integer to long. It promotes the narrower type to the wider type using well defined rules.
That makes sense, thanks for the clarification =)
Thanks #TarikNaej and #dhayden
Topic archived. No new replies allowed.