Nic*_*eed 9 c c++ function-prototypes
从功能和语法上来说,原型为int foo(void)和的函数之间是否有区别int foo(void *)?
我知道,例如之间的差异,int bar(int)以及int bar(int *)-其中之一是寻找一个int,另一种是找一个int指针。void行为是否相同?
Nic*_*eed 10
根据有关软件工程的答案, 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 type
Run Code Online (Sandbox Code Playgroud)
main.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);
^
Run Code Online (Sandbox Code Playgroud)
同样,用类型声明一个变量也是不可能的void:
main.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);
^
Run Code Online (Sandbox Code Playgroud)
main.c:5:8: error: variable has incomplete type 'void'
void qux;
Run Code Online (Sandbox Code Playgroud)
void作为函数的返回值表示不会返回任何数据。由于无法声明类型的变量void,因此即使使用void指针也无法捕获void函数的返回值。
int main(void) {
void qux; //trying to create a variable with type void
}
Run Code Online (Sandbox Code Playgroud)
main.c:5:5: error: assigning to 'void *' from
incompatible type 'void'
j = foo(0);
^ ~~~~~~
Run Code Online (Sandbox Code Playgroud)
无类型void *是另一种情况。空指针指示指向内存中某个位置的指针,但不指示该指针处的数据类型。(这是用于在C中实现多态性的功能,例如使用qsort()函数。)但是,使用这些指针可能很棘手,因为很容易将它们意外地转换为错误的类型。以下代码不会在中引发任何编译器错误C,但会导致未定义的行为:
main.c:5:8: error: variable has incomplete type 'void'
void qux;
Run Code Online (Sandbox Code Playgroud)
但是,以下代码完全合法。向和从空指针进行强制转换永远不会更改其持有的值。
void foo(int i) { return; }
int main(void) {
void *j;
j = foo(0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
47.200000
作为函数参数,void *它指示您所传入的指针处的数据类型未知,并且程序员(您)应自行决定如何正确处理该内存位置的内容。作为返回值,void *表示所返回的数据类型未知或为无类型,必须由程序进行处理。
main.c:5:5: error: assigning to 'void *' from
incompatible type 'void'
j = foo(0);
^ ~~~~~~
Run Code Online (Sandbox Code Playgroud)
tl; dr void在函数原型中表示“无数据”,表示没有返回值或参数,void *在函数原型中表示“该函数给出的指针处的数据不具有已知类型”,并表示参数或返回值必须先将其指针转换为其他类型,然后才能使用该指针上的数据。
foo(void)- 不带参数的函数
foo(void *)- 具有一个void *参数的函数
什么是void *?它只是指向没有指定类型的数据的指针。它可以转换为任何其他指针类型
unsigned add(void *arr)
{
unsigned *uarr = arr;
return uarr[0] + uarr[1];
}
Run Code Online (Sandbox Code Playgroud)