简体   繁体   中英

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? 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. I tried adding a redundant return 0 but that messes up the output I want.

Any advice?

If the function "reaches" the end brace it returns. 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:

from C99 6.9.1 Function definitions:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

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,

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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