Deep Exploration of void and void pointers in c\c++ __c++

Source: Internet
Author: User

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.

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 is compiled

Translation error:

void *p1;
int *p2;
P2 = p1;


Hint "' = ': cannot convert from ' void * ' to ' int * '".

Use of 3.void

The usage rules for the VOID keyword are given below:


Rule one if the function does not return a value, it should be declared as a void type

In C, a function that is not qualified with a return value type is processed by the compiler as a return integer value. But many programmers mistakenly assume that they are of type void. For example:

Add (inta, int b)
{
return a + B;
}
int main (int argc, char* argv[])
{
printf ("2 + 3 =%d", add (2, 3));
}


The result of the program running is output:
2 + 3 = 5
This means that a function that does not have a return value description is indeed an int function.

Lin Rui "high quality C + + programming" (Modified electronic HD version download address: http://fishc.com/a/book/C__/648.html) mentioned: "C + + language has a very strict type of security check, do not allow the above situation (refers to the function without type declaration) occurs." However, the compiler does not necessarily think so, for example, in the visualc++6.0 of the Add function compiled without error and no warning and run correctly, so you can not hope that the compiler will do a rigorous type check.

Therefore, in order to avoid confusion, we must specify the type of any function, without omitting it, when writing a C + + program. If the function does not return a value, be sure to declare it as a void type. This is not only the need for good readability of the program, but also the requirements of programming standardization. In addition, with the void type declaration, you can also play the "Self annotation" function of the code. The code's "self annotation" means that the code can annotate itself.

Declare one of these functions in the C + + language:

Intfunction (void)
{
return 1;
}


It is not legal to make the following call:

function (2);


Because in C + +, the function argument is void means that the function does not accept any arguments.

We compile in Turbo C 2.0:

#include "stdio.h"
Fun ()
{
return 1;
}
Main ()
{
printf ("%d", Fun (2));
GetChar ();
}


Compilation is correct and output 1, which means that in C, you can pass any type of parameter to a function without parameters, but compiling the same code in the C + + compiler

Wrong. In C + +, you cannot pass any arguments to a function that has no parameters, and the error prompts "' Fun ': function does not take 1parameters."

So, whether in C or C + +, if the function does not accept any arguments, be sure to indicate that the parameter is void.

  

Rule two carefully use void pointer type

According to the ANSI (Americannational standards Institute) standard, you cannot perform an algorithmic operation on a void pointer, that is, the following operations are illegal:

void *pvoid;
pvoid++; ANSI: Error
PVOID + 1; ANSI: Error
The ANSI standard is so determined because it insists that the pointer to an algorithmic operation must be determined to know its point to the data type size.
For example:
int *pint;
pint++; ANSI: Correct


The result of pint++ is to make it larger sizeof (int).

But the infamous GNU (GNU ' snot UNIX acronym) is not so determined, it specifies void * 's algorithm operation and char * consistent.

The following statements are therefore correct in the GNU compiler:

Pvoid++;//gnu: Right
PVOID + 1; GNU: Right


The result of the pvoid++ was that it increased by 1.

In the actual program design, in order to meet the ANSI standard and improve the portability of the program, we can write code to achieve the same function:

void *pvoid;
(char *) pvoid++; ANSI: correct; GNU: Correct
(char *) pvoid + + 1; ANSI: Error; GNU: correct


There are some differences between GNU and ANSI, and the GNU is generally more "open" than ANSI, providing support for more syntax. But in real design, we should try to

Able to meet ANSI standards.

  

Rule three if the parameter of a function can be any type of pointer, declare its argument to void *

Typical function prototypes such as memcpy and memset for memory manipulation functions are:

void *memcpy (void *dest, const void *SRC, size_t len);
void * memset (void * buffer, int c, size_t num);


In this way, any type of pointer can be passed into memcpy and memset, which also truly reflects the meaning of the memory manipulation function, because it operates on an object that is only a single

Save, regardless of what type of memory this piece is. If the parameter types of memcpy and memset are not void *, but char *, that's shouting strange. Such a memcpy and

Memset is obviously not a "pure, out of the vulgar" function.


The following code executes correctly:

Example: memset accept any type of pointer
int intarray[100];
memset (intarray, 0, 100*sizeof (int)); Will intarray clear 0

Example: memcpy accept any type of pointer
int intarray1[100], intarray2[100];
memcpy (Intarray1, Intarray2, 100*sizeof (int)); Copy the Intarray2 to Intarray1.


Interestingly, the memcpy and memset functions return a void * type, and how knowledgeable the creator of the standard library functions is.

  

Rule four void does not represent a true variable

The following code attempts to make void represent a real variable and is therefore the wrong code:

void A; Error
function (void a); Error


Void embodies an abstraction, the world's variables are "type", such as a person is not a man is a woman (and a transvestite.) )。

Void appears only for an abstract need, and it is easy to understand the void data type if you correctly understand the concept of "abstract base class" in object-oriented objects. As

You cannot define an instance of an abstract base class, nor can we define a void (a "abstract data type" variable that we would like to refer to as "void").

4. Summary
Small void contains a wealth of design philosophy, as a program designers, the problem of a deep level of thinking will certainly make us benefit.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.