gpt4 book ai didi

c - 在 C 中的函数中是否必须使用 "return"和 "void"?

转载 作者:太空狗 更新时间:2023-10-29 15:11:31 24 4
gpt4 key购买 nike

示例:

void Function(int Number)
{
process.....

**return;**
}

是否必须在每个函数的末尾使用“return”?

示例 2:

void Function(**void**)
{
process...
}

如果我没有收到任何值,是否有必要在参数列表中使用“void”?

有人说不行,有人说行。什么是对编译器的完美理解和 C 语言的最佳实践?

最佳答案

遗漏void in parameters 意味着该函数接受任意数量的参数:

假设一个程序:

void func() {
}

void func2(void) {
}

int main(void) {
func(2);
func2(2);
}

现在用 gcc -std=c11 -Wall -pedantic test.c 编译它,您会收到来自 func2 的错误仅:

test.c: In function ‘main’:
test.c:9:5: error: too many arguments to function ‘func2’
func2(2);
^
test.c:4:6: note: declared here
void func2(void) {

也就是说,调用void func(); 不是GCC 的编译时错误带有参数,而调用 void func2(void) 是编译时错误与论据。即使该函数没有任何参数,仍然可以使用任意数量的参数调用它。

然而,即使这确实可以编译,6.5.2.2 函数调用也会指出“如果参数的数量不等于参数的数量,则行为是未定义的。” (func 是用 1 个参数调用的,但没有参数)。


C11 标准 n1570 工作草案说明如下:

6.11.6 Function declarators

  1. The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

(有趣的事实:标准本身在其示例中使用 int main())。


至于return语句,如果它是最后一条语句,则可以从返回 void 的函数中省略它。 Return 有 2 种用途 - 终止函数的执行并指定返回给调用者的值。

标准草案说:

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

这里的 Any 意味着返回值的函数或不返回值的函数(返回 void )都允许没有 return声明。

草案中关于函数声明的 6.9.1 说:

  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

因此,如果函数返回一个值(不是 void ),并且调用者使用该值,则省略 return 语句是未定义的行为。 (作为一个异常(exception),该标准还指出,省略 return 中的 main() 语句是现在等同于返回 0 的指定行为)。

关于c - 在 C 中的函数中是否必须使用 "return"和 "void"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29326149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com