如果void()不返回值,为什么我们使用它? [英] If void() does not return a value, why do we use it?
问题描述
void f()
表示 f
不返回任何内容。如果 void
不返回任何内容,那么为什么我们使用它呢?当发明C时, void
?
int
(同样适用于参数)。但是通常你写的函数做的东西,不需要返回任何东西(例如关于一个函数,只是打印一些东西在屏幕上)。出于这个原因,决定,为了指定你不想返回任何东西,你必须使用 void
关键字作为返回类型。
请记住, void
特别是:
-
如果将它指定为函数的参数列表,则意味着函数不带参数;这在C中是需要的,因为没有参数的函数声明意味着编译器参数列表只是未指定。在C ++中不再需要这个,因为空参数列表意味着函数不允许有参数;
-
void
也在指针中有重要作用;
void *
(及其变体)意味着指向未指定的东西。这是有用的,如果你必须写入必须存储/传递指针,而不实际使用它们的函数(只在结束时,实际使用指针,需要转换为适当的类型)。 -
,转换为
(void)
通常用于将某个值标记为故意未使用,从而抑制编译器警告。int somefunction(int a,int b,int c)
{
(void)c; // c保留供将来使用,杀死未使用的参数警告
return a + b;void f()
means thatf
returns nothing. Ifvoid
returns nothing, then why we use it? What is the main purpose ofvoid
?解决方案When C was invented the convention was that, if you didn't specify the return type, the compiler automatically inferred that you wanted to return an
int
(and the same holds for parameters).But often you write functions that do stuff and don't need to return anything (think e.g. about a function that just prints something on the screen); for this reason, it was decided that, to specify that you don't want to return anything at all, you have to use the
void
keyword as "return type".
Keep in mind that
void
serves also other purposes; in particular:if you specify it as the list of parameters to a functions, it means that the function takes no parameters; this was needed in C, because a function declaration without parameters meant to the compiler that the parameter list was simply left unspecified. In C++ this is no longer needed, since an empty parameters list means that no parameter is allowed for the function;
void
also has an important role in pointers;void *
(and its variations) means "pointer to something left unspecified". This is useful if you have to write functions that must store/pass pointers around without actually using them (only at the end, to actually use the pointer, a cast to the appropriate type is needed).also, a cast to
(void)
is often used to mark a value as deliberately unused, suppressing compiler warnings.int somefunction(int a, int b, int c) { (void)c; // c is reserved for future usage, kill the "unused parameter" warning return a+b; }
这篇关于如果void()不返回值,为什么我们使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!