Switch case doesn't call the functions inside them

时间:2018-02-03 11:01:38

标签: c++ visual-studio

The problem is that cases don't call the functions inside them. Why don't the switch case call the functions inside them?

void admin_menu()
{

system("cls");
int x;

cin >> x;
switch (x)
{
    case '1':
        write_student();
        break;

    case '2':
       return;

    default:
        cout << "\a";
}
}

2 个答案:

答案 0 :(得分:3)

'1' has a type of char, not int, but you read ints. So you have a wrong comparison inside the switch statement: '1' and '2' are converted to int before being compared to x, so the result is not what you have expected.

If you read ints, then the switch should be:

switch (x)
{
    case 1:
        write_student();
        break;

    case 2:
       return;

    default:
        std::cout << "\a";
}

答案 1 :(得分:1)

Your constant_expression in case label is a character literal. It will be promoted / converted to int as x is of type int. Characters have underlying integer values and are implicitly convertible to integers. The character literal of '1' corresponds to an integral value of 49 and character literal of '2' corresponds to integral value of 50. So effectively with your code you have (assuming ASCII encoding):

switch (x)
{
    case 49:
        write_student();
        break;

    case 50:
       return;
//

Remove the single quotes and use integral literals instead of character literals:

switch (x)
{
    case 1:
        write_student();
        break;

    case 2:
       return;
//

For more info explore the switch statement reference.