(i) the meaning of void
Void literally means "no type", and void is almost only "annotated" and restricts the function of the program, since no one will ever define a void variable, let's try to define:
void A;
This line of statement compiles with an error, prompting "illegal use of type ' void '". However, even if the compilation of void A does not go wrong, it does not have any practical significance.
Void really plays a role in:
(1) The qualification of function return;
(2) The qualification of function parameters.
int f (void); equal to int f (); void f ();
(ii) void* hands
C + + provides a special pointer type void*, which can hold the address of any type of object, void* indicates that the pointer is related to an address value, but it is unclear what type of object is on this address. The void* pointer supports only a few limited operations:
1. Compare with another pointer
2. Passing a void* pointer to a function or returning a void* pointer from a function
3. Assign a value to another void* pointer
4. Do not allow to manipulate the object it points to with the void* pointer
Because other pointers contain address information, assigning the values of other pointers to null type pointers is legal, whereas assigning null-type pointers to other pointers is not allowed unless explicitly converted.
Thus, the role of void* is broadly as follows:
1. Reference: Common Type
Can be used as a function template, linked list parameters such as the general parameters. When you use it, you only need to force the type conversion.
In WinSocket programming, the parameter of the _beginthread () function is an instance of using void*.
2. Forcing type conversions
Sometimes due to overloading and other disturbances, resulting in the need to convert to void *, to take the address.
For example, (void *) Obj.member, the address of member can be taken, and the direct & (Obj.member) is actually the starting address of obj.
3. Point to the 0 address
(void *) 0, pointing to an address that is all 0, equivalent to NULL.
A non-void type is explicitly converted to a void type expression, and is used to avoid warnings from some code static checker tools.
#include <iostream> #include <string>using namespace Std;int main () {double Obj=3.14;int a=7;double *pd= &obj;void *pv=&obj; OK pv=&a; OK (*PV) + +;//error, do not manipulate object int *ptr=&a;void *p=ptr;//okptr=p;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + Primer learning notes and thinking _7 void and void* pointers usage