The following function successfully compiles and prints hello 5
on gcc 8.3 running on Debian:
#include <stdio.h>
int* bar(int* x) {}
int main() {
int x = 5;
int* p = bar(&x);
printf("hello %dn", *p);
}
I’m confused about the function bar
. It’s declared as int*
but the body is empty, so I didn’t actually tell it to return anything. More concerning, why does the program behave as if I had said return x;
in the body of bar
? Is this behavior that is specified somewhere or is it just an accident?
2
Answers
The C standard does not require a function declared with a non-void return type to return a value.
The standard says that if a function returns without returning a value (because execution flows to its closing
}
) and the value of the function is used, then the behavior is not defined. However, there are situations where it makes sense for a function to return a value in some cases and not others. For example, you can have a function that sets or gets a value depending upon a command parameter:Doing this is unusual (and may not be good design), so a compiler may warn about it. However, to conform to the C standard, a C implementation must not reject a non-void function in which control may reach the closing
}
.The standard has the following to say about return statements:
ISO/IEC 9899:2018 §6.8.6.4 The return Statement passage 2
This means that the compiler has to allow non void functions that have no (or no reachable) return statement, in order to be in compliance with the standard.
This leaves the return value as undefined behavior.
In this case the register used for the first function argument is also the register used for the return value.