C 中的隐式 return 值,在应该 return 非空的函数中没有显式 return
implicit return value in C with no explicit return in a function that should return non-void
我有一些遗留的 C 代码,是我在 Linux 上使用 gcc 4.9.2 版编译的,在 [-Wreturn-type] 上带有 return-type 警告。我的功能如下:
int somefn() {
// .. do something ..
// no explicit return statement
}
来电者的来电如下:
if (somefn()){
// handling of success
}
else {
// handling of failure
}
当警告被抑制时,编译+链接一切正常,而在运行时,我们可能会感到惊讶,会出什么问题?
我在 Linux 上使用 gcc 4.9.2 版编译,在 [-Wreturn-type]
上出现 return 类型的警告
调用者期望 true(在 C 中,解释为非零)表示成功,0 表示失败。这就是正在发生的事情。由于 return 是非空函数,因此在调用时会在堆栈上为 return 值创建 space,然后将上下文切换到被调用方,最后,当控制返回给调用者,上下文切换回从堆栈中弹出所有局部变量,并将 return 值保留在堆栈上,以便在从被调用者 return 之后由调用者弹出。因此,没有明确的 return 语句会导致某些值被 returned。这相当于将显式 return 语句作为“return 1;”或 'return 0;' 视情况而定。所以,更好的(当然)是有明确的 return 声明,例如
int somefn() {
// .. do something ..
if (..somecond..)
return 0; // failure
else
return 1; // success
}
为了避免意外,我想说,编译器应该将 'no return statement in function returning non-void'
标记为错误。
引用 C11
,章节 §6.9.1,函数定义,语义
If the }
that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined.
因此,该标准指定了函数定义的语义,并明确指出(对于非空函数 return 类型)一个函数在没有 return 语句和 returned 值用于调用方原因 undefined behavior。
因此,它接受在句法上编写这样的函数是可能的,但尝试使用它将是 UB。它没有将此声明为违反约束,我认为符合标准的编译器没有理由生成 "error".
如果您需要严格检查(顺便推荐一下),请使用 -Werror
选项。
我有一些遗留的 C 代码,是我在 Linux 上使用 gcc 4.9.2 版编译的,在 [-Wreturn-type] 上带有 return-type 警告。我的功能如下:
int somefn() {
// .. do something ..
// no explicit return statement
}
来电者的来电如下:
if (somefn()){
// handling of success
}
else {
// handling of failure
}
当警告被抑制时,编译+链接一切正常,而在运行时,我们可能会感到惊讶,会出什么问题?
我在 Linux 上使用 gcc 4.9.2 版编译,在 [-Wreturn-type]
上出现 return 类型的警告
调用者期望 true(在 C 中,解释为非零)表示成功,0 表示失败。这就是正在发生的事情。由于 return 是非空函数,因此在调用时会在堆栈上为 return 值创建 space,然后将上下文切换到被调用方,最后,当控制返回给调用者,上下文切换回从堆栈中弹出所有局部变量,并将 return 值保留在堆栈上,以便在从被调用者 return 之后由调用者弹出。因此,没有明确的 return 语句会导致某些值被 returned。这相当于将显式 return 语句作为“return 1;”或 'return 0;' 视情况而定。所以,更好的(当然)是有明确的 return 声明,例如
int somefn() {
// .. do something ..
if (..somecond..)
return 0; // failure
else
return 1; // success
}
为了避免意外,我想说,编译器应该将 'no return statement in function returning non-void'
标记为错误。
引用 C11
,章节 §6.9.1,函数定义,语义
If the
}
that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
因此,该标准指定了函数定义的语义,并明确指出(对于非空函数 return 类型)一个函数在没有 return 语句和 returned 值用于调用方原因 undefined behavior。
因此,它接受在句法上编写这样的函数是可能的,但尝试使用它将是 UB。它没有将此声明为违反约束,我认为符合标准的编译器没有理由生成 "error".
如果您需要严格检查(顺便推荐一下),请使用 -Werror
选项。