A deep exploration of C + + language void and void pointers

Source: Internet
Author: User

Turn from:http://www.lanou3g.com/blog/sort/SelfiOS/page/781. Overview Many beginners do not understand the type of void and void pointers in C + + languages, so there are some errors in their use. This article explains the profound meaning of the void keyword and details the use and techniques of void and void pointer types. 2.void meaning void literally means "no type",void * is "untyped pointer", void * can point to any type of data。   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 returns, (2) The qualification of function parameters.   We will specify the above two points in the third section. Knownif pointers P1 and p2 are of the same type, then we can assign values directly between P1 and P2, and if P1 and P2 point to different data types, you must use the force 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 P1 = P2 statement will compile error, prompt "' = ': cannot convert from ' int * ' to ' float * '", must be changed to: P1 = (float *) P2;  While void * is different, any type of pointer can be assigned directly to it without forcing the 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 forcing the type to convert. Because"No type" can contain "type", while "have type" cannot tolerate "no type"。 The truth is simple, we can say "men and women are people", 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 * '". 3.void usage rules for the VOID keyword are given below: rule one if the function does not return a value, it should be declared as void typein the C language, a function that is not qualified with a return value type is processed by the compiler as a return integer. But many programmers mistakenly think of it as 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 result of the program running is output: 2 + 3 = 5 This indicates that the function that does not add the return value description is indeed an int function. "The C + + language has very strict type security checks and does not allow this to happen (the function does not add a type declaration)," said Dr. Lin Rui, "high quality C + + programming".  However, the compiler does not necessarily think so, for example, in visual c++6.0 the above Add function compilation error-free and no warning and run correctly, so you can not hope that the compiler will do a strict type checking. So, in order to avoid confusion, when we write C + + programs,for any function, you must specify its type without a leak. If the function does not return a value, be sure to declare it as void type。 This is both the need for good readability of the program and the requirements of programming norms. In addition, the "self-commenting" function of the code can also be played after the void type declaration is added. The code's "self-explanatory" code can annotate itself. Rule TwoIf the function has no arguments, declare that its argument is voidDeclare one such function in the C + + language: int function (void) {return 1;}   It is not lawful to make the following call: function (2);   Because in C + +, the function parameter is void meaning 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 ();} Compile correctly and Output 1, which indicates thatIn the C language, you can pass arguments of any type to a function without parameters, but compiling the same code in the C + + compiler will make an error. In C + +, you cannot pass any parameters to a function that has no parameters.Error message "' Fun ': function does not take 1 parameters". Therefore, in C or C + +, if the function does not accept any arguments, be sure to indicate that the argument is void. Rule three caution use void pointer type according to ANSI (American National standards Institute) standard,cannot perform algorithmic operation on void pointersThat the following operations are illegal: void * pvoid;pvoid++; ANSI: Error pvoid + = 1; ANSI: Error//The ANSI standard is determined because it insists that the pointer to the algorithm operation must be determined to be aware of its point to the data type size. For example: int *pint;pint++; ANSI: The result of correct pint++ is to make it grow sizeof (int).However, the famous GNU (GNU's not UNIX abbreviation) does not assume that it specifies that the algorithm operation of Void * is consistent with char *. so the following statements are correct in the GNU compiler: pvoid++; GNU: Correct pvoid + = 1;   GNU: The result of correct pvoid++ is 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 that implements the same function: void * PVOID; (char *) pvoid++; ANSI: correct; GNU: Correct (char *) pvoid + = 1; ANSI: Error; GNU: There are some differences between correct GNU and ANSI, in general, the GNU is more "open" than ANSI and provides support for more syntax. But we should be able to meet the ANSI standards as much as possible when it comes to real design. Rule IVif the argument to a function can be any type of pointer, declare that its argument is void *Typical function prototypes such as memory manipulation functions memcpy and memset are: void * memcpy (void *dest, const void *SRC, size_t len); void * memset (void * buffer, int C, size_t num);Thus, any type of pointer can be passed into memcpy and memset,This also truly embodies the meaning of the memory manipulation function, because it operates on only one piece of memory, regardless of what type of memory it is。 If the parameter type of memcpy and memset is not void *, but char *, then shouting truth is strange! Such memcpy and memset are obviously not a "pure, out of the vulgar" Function! The following code executes correctly://Example: Memset accepts any type of pointer int intarray[100];memset (intarray, 0, 100*sizeof (int)); Intarray Clear 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 return a void * type, and the writer of standard library functions is so knowledgeable! Rule FiveVoid cannot represent a real variableThe code below attempts to have void represent a real variable, so it's all the wrong code: void A; Error function (void a); Error void represents an abstraction in which variables in the world are "typed", such as whether a person is a man or a woman (and a shemale?).   )。 Void appears only for an abstract need, and it is easy to understand the void data type if you correctly understand the concept of an object-oriented "abstract base class". Just as it is not possible to define an instance of an abstract base class, we cannot define a void (the "abstract data type") variable that allows us to compare. 4. Summing up the small void contains a very rich philosophy of design, as a program designer, a deep level of thinking about the problem will certainly benefit us.

Deep Exploration of void and void pointers (RPM)

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.