skip to Main Content

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


  1. 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:

    int AccessState(int Command, SomeStructure *S,...)
    {
        switch (Command)
        {
            case 0: // Get the state.
                return S->Value;
            case 1: // Set the state from the optional int parameter following S.
                 va_list ap;
                 va_start(ap, S);
                 S->Value = va_arg(S, int);
                 va_end(ap);
                 break;
        }
    }
    

    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 }.

    Login or Signup to reply.
  2. The standard has the following to say about return statements:

    ISO/IEC 9899:2018 §6.8.6.4 The return Statement passage 2

    A return statement terminates execution of the current function and returns control to its caller. A
    function may have any number of return statements.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search