1. Overview
Many beginners do not understand the type of void and void pointer in C + + language, so there are some errors in usage. This article will explain the profound meaning of the void keyword, and detail the methods and techniques for the use of void and void pointer types.
The meaning of 2.void
void literal means "no type", void * is "no type pointer" and void * can point to any type of data.
Void has almost only "annotation" and restriction programs, because no one ever defines a void variable, let's try to define:
void A;
This line of statements is compiled with an error, prompting "illegal use of type ' void '". However, even if void a compiles without errors, it has no practical significance.
Void really plays a role in:
(1) The qualification of function return;
(2) The qualification of function parameters.
We will specify the above two points in the third section.
As we all know, if pointers P1 and p2 are of the same type, then we can assign values to each other directly between P1 and P2, and if P1 and P2 point to different data types, you must use the coercion type conversion operator to convert the pointer type to the right of the assignment operator to the type of the left pointer.
For example:
float *p1;
int *p2;
p1 = p2;
where the P1 = P2 statement compiles an error that prompts "' = ': cannot convert from ' int * ' to ' float *" must be changed to:
P1 = (float *) P2;
But void * is different, any type of pointer can be directly assigned to it, without coercion type conversion:
void *p1;
int *p2;
p1 = p2;
This does not mean, however, that void * can also be assigned to other types of pointers without coercion of type conversions. Because "no type" can contain "have type", and "have type" cannot contain "no type". The reason is very simple, we can say "men and women are human", but can not say "man is a Man" or "man is a woman." The following statement compiles an error:
void *p1;
int *p2;
p2 = p1;
Hint "' = ': cannot convert from ' void * ' to ' int * '".