Profound analysis of void and void pointer meaning, void pointer Parsing

Source: Internet
Author: User

Profound analysis of void and void pointer meaning, void pointer Parsing
Rules for using the void Keyword:

1. If the function does not return a value, the void type should be declared;

2. If the function has no parameters, the void parameter should be declared;

3. If the function parameter can be of any type pointer, the parameter should be declared as void *;

4. void cannot represent a real variable;

Void represents an abstraction. All the variables in the world are "typed ".

######################################## #################################
1. Overview
Many beginners do not understand the void and void pointer types in C/C ++, so some errors have occurred in usage. This article will explain the profound meaning of the void keyword, and

Describes how to use the void and void pointer types.

2. Meaning of void
Void literally means "no type", void * is "no type Pointer", and void * can point to any type of data.

Void has almost only "Comments" and restrictions on the role of the program, because no one will ever define a void variable, let's try to define:


Void;

An error occurs when compiling this line of statements, and the message "illegal use of type 'void'" is displayed '". However, even if the compilation of void a does not go wrong, it has no practical significance.

Void actually plays the following role:
(1) Restrictions on function return;
(2) Restrictions on function parameters.

We will describe the above two points in section 3.

As we all know, if the pointer p1 and p2 are of the same type, we can directly assign values to each other between p1 and p2. If p1 and p2 point to different data types, we must use the forced type.

The conversion operator converts the pointer type on the right of the value assignment operator to the pointer type on the left.

For example:
Float * p1;
Int * p2;
P1 = p2;

The p1 = p2 statement will cause compilation errors and the prompt "'=': cannot convert from 'int * 'to 'float *'" must be changed:
P1 = (float *) p2;
Void * is different. pointers of any type can be directly assigned to it without forced type conversion:
Void * p1;
Int * p2;
P1 = p2;

However, this does not mean that void * can also be assigned to other types of pointers without force type conversion. Because "No type" can tolerate "type", while "type" cannot include

Supports "No type ". The principle is simple. We can say that "both men and women are people", but not "people are men" or "people are women ". The following statement compilation error:
Void * p1;
Int * p2;
P2 = p1;

The message "'=': cannot convert from 'void * 'to 'int *' is displayed *'".

3. Use of void

The following describes the rules for using the void Keyword:
Rule 1 if the function does not return a value, the void type should be declared.

In C language, any function without a limited return value type will be processed by the compiler as the return integer value. However, many programmers mistakenly think it is of the void type. For example:
Add (int a, int B)
{
Return a + B;
}
Int main (int argc, char * argv [])
{
Printf ("2 + 3 = % d", add (2, 3 ));
}

The program running result is output:
2 + 3 = 5
This indicates that the function without return values is indeed an int function.

Dr. Lin Rui mentioned in "High Quality C/C ++ programming": "The C ++ language has strict type security checks and does not allow the above situations (that is, the function does not add a type declaration) occurred ". However, compile

For example, in Visual C ++ 6.0, the compilation of the add function is error-free, warning-free, and runs correctly. Therefore, you cannot expect the compiler to perform a strict type check.

Therefore, in order to avoid confusion, when writing C/C ++ programs, you must specify the type of any function. If the function does not return a value, it must be declared as a void class.

Type. This is both a need for good program readability and a requirement for standardized programming. In addition, after adding the void type declaration, you can also use the "self-annotation" function of the Code. Self-injection of code

"Release" means the code can annotate itself.

Rule 2 If the function has no parameters, the parameter should be declared as void

Declare a function in C ++:
Int function (void)
{
Return 1;
}

The following call is invalid:
Function (2 );

In C ++, the function parameter void means that this function does not accept any parameters.

We compile in Turbo C 2.0:
# Include "stdio. h"
Fun ()
{
Return 1;
}
Main ()
{
Printf ("% d", fun (2 ));
Getchar ();
}

Compiling is correct and 1 is output. In C, parameters of any type can be transferred to a function without parameters. However, compiling the same code in C ++ compiler will cause an error. In C ++

".

Therefore, whether in C or C ++, if the function does not accept any parameters, you must specify the parameter as void.

Rule 3 be careful when using the void pointer type

According to the ANSI (American National Standards Institute) standard, you cannot perform algorithm operations on the void pointer, that is, the following operations are invalid:
Void * pvoid;
Pvoid ++; // ANSI: Error
Pvoid + = 1; // ANSI: Error
// The ANSI standard determines this because it insists that the pointer to the algorithm operation must be determined to know the data type it points.
// Example:
Int * pint;
Pint ++; // ANSI: Correct

The result of pint ++ is to increase sizeof (int ). (In VC6.0, the test is a multiple of sizeof (int)

However, the well-known GNU (GNU's Not Unix abbreviation) does Not recognize this as it specifies that the void * algorithm operation is consistent with char.

Therefore, the following statements are correct in the GNU Compiler:
Pvoid ++; // GNU: Correct
Pvoid + = 1; // GNU: Correct

The execution result of pvoid ++ is increased by 1. (In VC6.0, the test is a multiple of sizeof (int)

In actual programming, to cater to ANSI standards and improve program portability, we can write code that implements the same function as below:
Void * pvoid;
(Char *) pvoid ++; // ANSI: Correct; GNU: Correct
(Char *) pvoid + = 1; // ANSI: error; GNU: Correct

There are some differences between GNU and ANSI. In general, GNU is more open than ANSI and provides support for more syntaxes. However, we should try our best to cater to the actual design.

ANSI standard.

Rule 4 if the function parameter can be a pointer of any type, the parameter should be declared as void *

Typical function prototypes for memory operation functions such as memcpy and memset 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 truly reflects the significance of the memory operation function, because the object it operates on is only a piece of memory, not

The type of memory. If the parameter types of memcpy and memset are not void * But char *, it is really strange! Such memcpy and memset are obviously not

"Pure, out of low-level interesting" function!

The following code is correctly executed:
// Example: memset accepts any type of pointer
Int intarray [100];
Memset (intarray, 0,100 * sizeof (int); // clear intarray 0

// Example: memcpy accepts any type of pointer
Int intarray1 [100], intarray2 [100];
Memcpy (intarray1, intarray2, 100 * sizeof (int); // copy intarray2 to intarray1

Interestingly, the memcpy and memset functions also return the void * type. how knowledgeable are the compilers of the standard library functions!

Rule 5 void cannot represent a real Variable

The following code tries to make void represent a real variable, so it is all wrong code:
Void a; // Error
Function (void a); // Error

Void represents an abstraction in which all variables in the world are "typed". For example, a person is either a man or a woman (or a demon ?).

The emergence of void is only for an abstract need. If you have understood the concept of "abstract base class" in object-oriented, it is easy to understand the void data type. Just as you cannot smoke

The base class defines an instance, and we cannot define a void (let's say that void is "abstract data type") variable.

4. Summary
The small void contains a wealth of design philosophy. As a program designer, thinking deeply about the problem will inevitably benefit us a lot. No matter what type of pointer (void *, char *, int *, float *...) the default initial value is 0 xCCCCCCCC // This should be different from each compiler, this is for vc6

# Include <iostream. h>
# Include <memory. h>
// # Include <string. h>
Void main ()
{
Void * p1;
Int a = 10;
Int * p2 = &;
Cout <p1 <endl;
Cout <(int) * p2 <endl;
P1 = p2;
Cout <* (int *) p1 <endl ;//!!!!!!! Operation output value with null type!
Cout <(int) * p2 <endl;
}
/* Output:
0 xCCCCCCCC
10
10
10
*/

If the value is NULL at the same time, it is set to NULL immediately after the delete operation.


In the debug version, the default pointer initial value is 0 xCCCCCCCC, and in the Release version, the initial value is 0x0000000A (VC6.0 on my computer ). If a pointer does not have an appropriate initialization value for the moment, it should be set to NULL (0 ).
For good programming habits, if declare is a pointer, It is initialized to NULL. If it is a class member, it is initialize In the constructor. When the pointer is deleted, it is set to NULL.


0xCCCCCCCC is only an undefined pointer value generated by VC in the debug state. It is used to indicate that the pointer is not initialized and will not be equal to this value in the release state (unless coincidentally ). If a pointer does not have an appropriate initialization value for the moment, it should be set to NULL (0 ).

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.