C ++ if else 语句在开关大小写 - 解释

c++ if else statement in switch case - explanation

本文关键字:开关 大小写 解释 语句 if else      更新时间:2023-10-16

刚开始学习。我有一个关于开关语句中是否还有其他问题

这是代码

    switch (operation)
{
        case '+': 
        result = num1 + num2;
        cout << result << endl;
        break;
        case '-':
            result= num1-num2; cout << result<< endl; break;
        case '*':
            result= num1 * num2;
            cout << result<< endl;
            break;
        case '/':
            if (num2 == 0)
            {
                cout << "num2 cannot be zero - division with zero is not possible!n"; 
            }else{
                result= num1/num2;
            }
            cout << result << endl;
            break;


default:
    cout << "message!" << endl;
    break;
}

好的,此代码正在生成错误 - 运行时检查失败 #3 - 变量"result"未初始化而被使用。

如果我更改代码并在 Nessage 之后添加中断,则无法用 0 除法

            case '/':
            if (num2 == 0)
            {
                cout << "num2 cannot be zero - division with zero is not possible!n"; break;
            }else{
                rezultat = num1/num2;
            }
            cout << rezultat << endl;
            break;

一切都按预期工作。

谁能从程序逻辑方面澄清这里发生了什么? 这是否意味着即使满足条件,if语句的else块也在运行?

提前感谢!

因为如果0 num2则打印消息,然后尝试执行cout << result << endl;,结果仍未初始化

另一个可能的解决方法是:

case '/':
    if (num2 == 0)
    {
        cout << "num2 cannot be zero - division with zero is not possible!n"; 
    }else{
        result= num1/num2;
        cout << result << endl;
    }
    break;

在您的原始代码中,如果num2 == 0,则您的消息将发送到 cout ,但result没有被分配值。执行继续,紧跟在else块之后的行:

cout << result << endl;

从而生成错误。

在修改后的代码中,如果num2 == 0则行上的两个语句

cout << "num2 cannot be zero - division with zero is not possible!n"; break;

被处决。break;语句会导致在整个switch块结束后继续执行,因此cout << rezultat << endl;永远不会被执行。

希望在上面澄清您的问题,但您可能会删除多余的 从语句Switch cout<<result<<endl;并将其放在相同的语句之外,因为它是所有case中的公共部分,除了显示计算结果外什么都不做,类似于

 switch(operation)
 {
   case '+': /*your computation here*/ break;
   case '-': /*your computation here*/ break;
   case '*': /*your computation here*/ break;
   case '/': /*your computation here*/ break;
   default:  /*your message command here*/;
 }  
 cout<<result<<endl; /* since this line is common, and does nothing but prints the result */