【问题标题】:Why can't i check the return of a function with a switch?为什么我不能用开关检查函数的返回?
【发布时间】:2016-11-10 11:47:59
【问题描述】:

使用 if 语句可以检查整数函数的返回。 函数在 this 中执行。

if(!yourfunction)
{
     do something;
}
else
{
     do something else;
}

然而,在 switch 中同样的事情甚至不会执行该功能。为什么?

switch(yourfunction())
{
      case 1:
            do something;
      case 0:
            something else;
}

【问题讨论】:

  • 为什么这被否决了?
  • 可能的。但是,您的 switch 语句似乎使用了无效的语法。
  • @vortexman100 不是我的反对意见,但您的 switch 缺少大括号、中断和默认值。所以很难猜出你在问什么,你也不想解释到底是什么doesn't work
  • 您的意思是在switch 语句中,甚至没有调用yourfunction 吗?您需要创建一个Minimal, Complete, and Verifiable Example 并向我们展示。并告诉我们你如何检查yourfunction 是否被调用。你确定它实际上只返回01?它不能为“true”返回一些其他非零值?
  • 除了学习如何创建MCVE,还请read about how to ask good questions

标签: c if-statement switch-statement return


【解决方案1】:

可以做到 - 但是你的函数应该返回一个 int。

int foo(void) { return 1; }

int main(void)
{
    switch(foo()) {
    case 0:  
            printf("foo\n");
            break;
    case 1:  
            printf("bar\n");
            break;
    default:
            break;
    }   
    return 0;
}

正如,可以看出这是编译并运行的。

[09:36 PM] $ gcc -Wall -Werror switcht.c -o switcht
[09:36 PM] $ ./switcht 
bar
[09:36 PM] $

但是,如果您的函数返回 int 以外的任何内容,则它不会编译。比如foo()返回float

float foo(void) { return 1.0; }

然后:

[09:44 PM] $ gcc -Wall -Werror switcht.c 
switcht.c: In function ‘main’:
switcht.c:7:9: error: switch quantity not an integer
switch(foo()) {
     ^~~~~~
[09:44 PM] $

【讨论】:

  • OP 的问题中没有第三种情况。直译宁愿是case 0: /* do something */ break; default: /*do something else */ break;
  • 问题缺少函数的声明。你展示了一个(错误的)模式并推测了其余的模式。
猜你喜欢
  • 2019-09-13
  • 2019-01-08
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
  • 2020-07-01
  • 2011-09-07
相关资源
最近更新 更多