函数的 return 类型是否可以在其范围之外更改为 return 无值?

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

ANSI C 编程书(函数基础部分)指出 '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.'

一个函数怎么会在创建后有 return 值,而在另一个地方 return 没有值?当我在函数内部使用条件语句 return 一个值并且如果条件失败则没有值时,是否存在这种情况?

The ANSI C PROGRAMMING book…

ANSI C 标准已失效,除非使用使用它的古老软件,否则不应使用有关它的书籍。国际标准化组织(ISO)和国际电工委员会(IEC)目前发布了C标准。

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

函数的类型没有变化。例如,它的类型是“function returning int”(并且有任何参数)。它实际上是否 return 是一个值是执行时的行为问题,而不是类型问题。

… 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.'

是的,这是允许的。 C 2018 6.9.1 12 说:

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.

因此,一个函数可以通过让控制流到结束 } 来完成,只要调用者不使用该值,这是由 C 标准定义的。

例如,这允许函数根据情况 return 执行或不执行值,例如:

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));
}

尽管如此,C 的这一方面很少使用,主要是为了适应旧软件。良好的编程习惯会在新代码中避免它,并且编译有关到达非 void 函数末尾的警告会对此有所帮助。