何时以及为何应使用 void 作为 C 中函数的 return 类型?

When and why should I use void as the return type of a function in C?

我目前正在练习 C 并学习指针和数组。我看了一个教程,讲师把函数从int aFunction()改成了void aFunction()。当然,他没有说为什么——这就是我来这里的原因。所以我想知道:什么时候以及为什么有人应该使用 void 作为函数的 return 类型。

函数声明中函数名前面的标记是函数 returns 的值的类型。在这种情况下,只有一个标记,但类型名称可能包含多个标记。当你想return一个整数对象时,你可以指定return类型为int。当函数不会 return 任何东西时,你使用 void return 类型。

在 C 中,您必须告诉编译器您声明的变量的每种类型。这就是为什么你有 intchar*.

之类的东西

和函数的 return 值没有区别。编译器必须知道每个 return 类型的函数才能正常工作。现在如果你有一个像 add(int a, int b) 这样的函数,通常你会希望它的 return 类型是整数,这就是你将它定义为

的原因
int add(int a, int b)
{
    return a+b;
}

现在假设你有一个函数 return 什么都没有,现在你需要告诉你的编译器这个函数 return 什么都没有。这就是使用 void 的原因。当函数执行 某事 但最终不需要 return 调用它的程序的任何值时,您使用 void。喜欢这个:

void printAdd(int a, int b)
{
    printf(“a + b = %d”, a+b);
}

我们在这里做了很多事情,但是加法的结果没有return编辑或存储,而是打印到屏幕上。

您可以像这样使用第一个函数 add()

int abc = add(5, 7);
// abc is 12

而您只能使用第二个功能

printAdd(5, 7);
// you cannot store the value because nothing is returned.
// 5 + 7 = 12 is printed to the screen