简体   繁体   English

控制如何到达这个非void function的结尾?

[英]How does control reach the end of this non-void function?

int test_ex(int num) {
  
  if (num >= 1000) {
    printf("+");
  } else {
    return num;
  }
  
}

int main(void) {  
   test_ex(123812);
}

I'm confused here as est_ex returns an int, but both if/else clauses return ints, right?我在这里感到困惑,因为 est_ex 返回一个 int,但是 if/else 子句都返回 int,对吧? So how would it be possible for there to be a non-int return here, I've been stuck on this for a long time.那么这里怎么可能有非int的return呢,我纠结了好久。 I tried adding a redundant return 0 but that messes up the output I want.我尝试添加一个冗余的 return 0,但这弄乱了我想要的 output。

Any advice?有什么建议吗?

If the function "reaches" the end brace it returns.如果 function “到达”结束括号,它返回。 If it is supposed to return a value, then the behavior is undefined.如果它应该返回一个值,那么行为是未定义的。

Update: it is undefined behavior only if the return value of the function is used:更新:仅当使用 function 的返回值时才是未定义的行为:

from C99 6.9.1 Function definitions:来自 C99 6.9.1 Function 定义:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.如果到达终止 function 的 },并且调用者使用 function 调用的值,则行为未定义。

Since the snippet of code in the example doesn't use the return value, there is no undefined behavior.由于示例中的代码片段不使用返回值,因此不存在未定义的行为。

You are missing that you do not return any int if num >= 1000 so,你错过了如果 num >= 1000 你不返回任何 int 所以,

int test_ex(int num) {
  // No matter you should return
  if (num >= 1000) {
    printf("+");
    return num;
  } else {
    return num;
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM