[SOLVED] Can the return type of a function be altered outside of it's scope to return no value?

Issue

The ANSI C PROGRAMMING book (basics of functions section) states ‘Control also returns to the caller with no value when the execution "falls off the end" of the function by reaching the closing right brace. It is not illegal, but probably a sign of trouble, if a function returns a value from one place and no value from another.’

How can a function once created with a return value, return no value in another place? Is it in a circumstance when I use a conditional statement inside the function to return a value and no value if the condition fails?

Solution

The ANSI C PROGRAMMING book…

The ANSI C standard is defunct, and books about it should not be used except when working with ancient software that used it. The International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC) currently publish a C standard.

Can the return type of a function be altered outside of it’s scope to return no value?

There is no change in the type of a function. Its type is, for example, “function returning int” (and having whatever parameters). Whether it actually returns a value or not is a matter of behavior at execution time, not of type.

… Control also returns to the caller with no value when the execution "falls off the end" of the function by reaching the closing right brace. It is not illegal, but probably a sign of trouble, if a function returns a value from one place and no value from another.’

Yes, this is allowed. C 2018 6.9.1 12 says:

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.

Thus a function may complete by letting control flow to the closing }, and this is defined by the C standard as long as the caller does not use the value.

This permits, for example, functions that do or do not return a value depending on circumstances, such as:

enum Command { Set, Get };


int GetOrSetValue(enum Command Command, int NewValue)
{
    static int SavedValue;

    switch (Command)
    {
        case Set:
            SavedValue = NewValue;
            break;
        case Get:
            return SavedValue;
    }
}


#include <stdio.h>


int main(void)
{
    //  Set saved value without using function return value.
    GetOrSetValue(Set, 4);

    //  Use function return value ot get saved value.
    printf("%d\n", GetOrSetValue(Get, 0));
}

Nonetheless, this aspect of C is rarely used and exists largely to accommodate old software. Good programming practice avoids it in new code, and compiling warnings about reaching the end of a non-void function assist with that.

Answered By – Eric Postpischil

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.