cfunctionunsigned

Do unsigned functions have to return something?


I'm working on an exercise where I have to program an unsigned function in C. Do I have to return something because of the type of the function? Or is it optional?


Solution

  • In normal use, any function declared to return a value ought to return a value. This is largely a matter of good programming practice. Failing to return a value is often a sign of an error. However, this is not required by the C standard, and there are two exceptions.

    C 2018 6.9.1 12 allows a function to terminate by reaching the end of its code without returning a value, provided the caller does not use the value of the function:

    Unless otherwise specified, if the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

    One case where a function might return a value in some situations and not in others is where it is designed to perform various different actions upon command. For example:

    unsigned DoSomething(int command, int parameters[])
    {
        switch (command)
        {
            case GetSomething:
                …
                return Something;
            case RememberSomething;
                Something = parameters[0];
                …
                break;
        }
    }
    

    Such designs may be error-prone and ought to be considered carefully. Since the function is declared to return a value, a programmer might expect it to do so and inadvertently assign the value of the function to another object in a situation where no value is returned, resulting in undefined behavior.

    Additionally, a function may not return at all, and there is a function specifier for explicitly telling the compiler this is so, _Noreturn, as specified in 6.7.4. This behavior is typically used only in abnormal situations. For example, the standard functions abort and exit terminate the program, so they do not return. Of course, they are declared with void, so they never return anything. However, you might have a function that calls exit in some circumstances and returns an integer in others.