【问题标题】:Why is this function returning the ASCII value if there is no match in switch cases?如果在 switch case 中没有匹配,为什么这个函数会返回 ASCII 值?
【发布时间】:2017-07-27 08:54:10
【问题描述】:
int foo(char c)
{
  switch(c)
  {
    case '1':
     return(1);
    case '2':
    return(2);
  } 
}

int main()
{
cout << foo('a');
}

这个程序打印 97 。

** 如果没有任何 switch case 匹配,它将打印 ASCII 值作为输出。 如果没有一个案例匹配,为什么函数返回 ASCII 值**

【问题讨论】:

  • 未定义的行为。你必须返回一个值;
  • 如果switch 中的所有案例都不匹配,你会从foo 返回什么?未从声明为执行的函数返回任何内容会导致未定义的行为,这会使整个程序格式错误且无效。
  • 不要让return 看起来像一个函数。
  • 请启用编译器警告。 警告 C4715:'foo':并非所有控制路径都返回值
  • @CIsForCookies 不过,我会坚持我的说法。 YMMV。 :)

标签: c++ switch-statement


【解决方案1】:

您的程序行为是未定义:对于任何返回intmain 除外)的函数,您必须有一个明确的返回值。

(您似乎观察到的是堆栈损坏;97 是您作为函数参数传递的小写字母 a 的 ASCII 值)。

【讨论】:

  • 我在 DEV c++ 中运行,它运行没有任何错误并打印输出
  • @Kishore:绝对:这是未定义行为的可接受表现。
  • 现在我知道输出是由于堆栈损坏造成的。但是它应该不会返回错误“到达非 void 函数的末尾”
  • @Kishore 编译器 告诉你。 C 本身没有固有的错误检查。
  • @WeatherVane 现在我启用了编译器警告。非常感谢
【解决方案2】:

您在这里拥有的是 UB。 foo 函数得到一个它无法处理的输入,因为您的案例都不支持输入 'a'。引擎盖下可能发生的事情(如果我可以尝试在您的特定情况下解释这个 UB)是 foo 返回它被转换为 int 的输入,这意味着 cout &lt;&lt; (int)('a');

对于这种情况,您的开关盒应包含default,例如:

int foo(char c)
{
  switch(c)
  {
    case '1':
      return(1);
    case '2':
      return(2);
    default:
      return (-1); // indicates error!!
  } 
}

int main()
{
int tmp = foo('a');
if (tmp != -1)
    cout << tmp;
else
    cout << "bad input";
}

【讨论】:

    【解决方案3】:
    int foo(char c) {
        switch(c) {
            case '1':
              return(1);
            case '2':
              return(2);
    
            //code to execute if 'c' does not equal the value following any of the cases
            default:
              return(-1);
        } 
    }
    
    int main() {
        cout << foo('a');
    }
    

    // simple char to int without switch
    int foo(char c) {
    
       /*
       // reject unwanted char 
       if (c=='a') {
           return -1;
       }
       */
    
       // convert char to int
       return (int)c;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多