从功能和语法上讲,原型为int foo(void)和int foo(void *)的函数之间是否有区别?
例如,我知道int bar(int)和int bar(int *)之间的区别--其中一个在寻找int,另一个在寻找int指针。void的行为是一样的吗?
发布于 2019-11-12 16:17:21
根据使用方式,这个关于软件工程的答案,对void进行了特殊处理。在C和C++中,void用于指示没有数据类型,,而void *用于指示不能单独解除引用的指向内存中没有类型的数据/空间的指针。 void *,必须先将其转换为另一种类型。此强制转换不需要在C中显式,而必须在C++中显式。(这就是为什么我们不转换malloc的返回值,即void *)。
当将函数用作参数时,void意味着完全没有任何参数,并且是唯一允许的参数。试图像使用变量类型一样使用void或包含其他参数会导致编译器错误:
int foo(void, int); //trying to use "void" as a parameter
int bar(void baz); //trying to use "void" as an argument's typemain.c:1:8: error: 'void' must be the first and only parameter if specified
int foo(void, int);
^
main.c:2:14: error: argument may not have 'void' type
int bar(void baz);
^用void类型声明变量也是不可能的。
int main(void) {
void qux; //trying to create a variable with type void
}main.c:5:8: error: variable has incomplete type 'void'
void qux;void作为函数的返回值表示不返回任何数据。由于不可能声明一个类型为void的变量,因此不可能捕获void函数的返回值,即使使用一个空指针也是如此。
void foo(int i) { return; }
int main(void) {
void *j;
j = foo(0);
return 0;
}main.c:5:5: error: assigning to 'void *' from
incompatible type 'void'
j = foo(0);
^ ~~~~~~无类型的void *是另一种情况。空指针指示指向内存中某个位置的指针,但不指示该指针的数据类型。(这是用于在C中实现多态性,比如qsort()函数)。然而,这些指针可能很难使用,因为很容易意外地将它们转换为错误的类型。下面的代码不会在C中抛出任何编译器错误,但会导致未定义的行为:
#include <stdio.h>
int main(void) {
double foo = 47.2; //create a double
void *bar = &foo; //create a void pointer to that double
char *baz = bar; //create a char pointer from the void pointer, which
//is supposed to hold a double
fprintf(stdout, "%s\n", baz);
}然而,以下代码是完全合法的;向空指针和空指针之间的转换从不更改它所持有的值。
#include <stdio.h>
int main(void) {
double foo = 47.2;
void *bar = &foo;
double *baz = bar;
fprintf(stdout, "%f\n", *baz);
}47.200000
作为一个函数参数,void *表示您要传入的指针上的数据类型是未知的,应该由程序员来正确处理该内存位置上的任何内容。作为返回值,void *表示正在返回的数据类型不为已知或没有类型,必须由程序处理。
int quux(void *); //a function that receives a pointer to data whose type is not known, and returns an int.
void *quuz(int); //a function that receives an int, and returns a pointer to data whose type is not known.tl; void博士在函数原型中的意思是“无数据”,并表示没有返回值或无参数,而函数原型中的void *则表示“给定的指针处的数据没有已知类型”,并指示必须将指针转换为不同类型的参数或返回值,然后才能使用指针处的数据。
发布于 2019-11-12 16:20:18
foo(void) -无参数函数
具有一个foo(void *)参数的void *函数
void *是什么?它只是指向没有指定类型的数据的指针。它可以转换为任何其他指针类型。
unsigned add(void *arr)
{
unsigned *uarr = arr;
return uarr[0] + uarr[1];
}发布于 2019-11-12 16:47:17
从功能和语法上讲,其原型为int foo(void)和int foo(void *)的函数之间是否有区别?
这是有区别的:
int foo(void)声明了一个不接受参数的函数。
int foo(void *)声明了一个函数,它接受void*类型的单个参数。
在C++中,int foo(void)与int foo()是等价的。
https://stackoverflow.com/questions/58822654
复制相似问题