The use of variable parameters in C language

Source: Internet
Author: User

Objective

The functions we use most in C programming must include printf and many similar variants. This function is included in the C library function, defined as int printf (const char* format, ...);

In addition to a format string, you can enter more than one variable parameter, such as:

  printf ("%d", I);
 printf ("%s", s);
  printf ("The number is%d, string is:%s", I, s);

To determine the format string for the rest of the chapter, the following is an analysis of the implementation details of variable parameters.

One, simple example

intSimpleintnum,...) {        intI, result=0;     Va_list VL; //va_list pointer for va_start variable parameter, char*Va_start (Vl,num);//get the first value in a mutable argument listprintf"num:%d, vl:%d\n", num,*VL);  for(i =0; I < (num-1); i++)//here num indicates how many parameters are in the mutable argument list{result= Va_arg (VL,int);//here, the VL skips backwards by 4 bytes (sizeof (int) size) to the next parameter, returning the current argument (not theone parameter) printf ("in for result:%d, *vl:%d\n", result, *VL);//printed here, it can be seen that the VL always points to the parameter behind result} va_end (VL);//End Flag    returnresult;}intMainintargcChar**argv) {        intnum =argc; inti =0; Simple (5,1,2,3,4,5); return 1;}

The results of the operation are as follows:

[email protected]:~/own$./varlist                num:5, VL:1in for  result: 1,  *VL:2in  for result:2,  *VL:3    in to result:3,  *VL:4in for  result: 4,  *VL:5
Two. Introduction to related APIs

The implementation of a mutable parameter list is made up of several macros, in the file include/stdarg.h:

  Va_list defines a variable, defined in the kernel:

    Char *va_list; // character pointer type  

Va_start (AP, type) starts getting the first parameter in the mutable argument list (...). The first one inside), that is, skipping the first parameter (that is, num):

#ifndef __sparc__#defineVa_start (AP, lastarg) \(AP= ((Char*) & (Lastarg) + __va_rounded_size (lastarg)))//AP refers to the next parameter, Lastarg unchanged#else#defineVa_start (AP, lastarg) \(__builtin_saveregs (), AP= ((Char*) & (Lastarg) + __va_rounded_size (lastarg)))//Skip the first parameter, point to the second parameter memory address#endif//take the integer 4 of the int to the type up, and multiply by the int integer 4#define__va_rounded_size (TYPE) \  (((sizeof(TYPE) +sizeof(int) -1) /sizeof(int)) *sizeof(int))

Va_arg (args, int) loops through the parameters in the mutable argument list, args refers to the next parameter address, and the current parameter address is returned.

//First=va_arg (args,int)#defineVa_arg (AP, TYPE) \//AP points to the next type of parameter(AP+ = __va_rounded_size (TYPE), \//returns the ap-sizeof (type) parameter, which is the previous argument* ((TYPE *) (AP-__va_rounded_size (TYPE) )))//take the integer 4 of the int to the type up, and multiply by the int integer 4#define__va_rounded_size (TYPE) \  (((sizeof(TYPE) +sizeof(int) -1) /sizeof(int)) *sizeof(int))

The last Va_end (AP) End flag, which may just be the end of a mutable parameter list in the program (Stdarg.h only defines the next, not implemented part of the code).

Three. Variable Counselor application is a matter of caution

   becauseVa_start, Va_arg, Va_endand other definitions macro,so it looks stupid .,The type and number of variable parameters are completely controlled by the program code in the function.,It does not intelligently identify the number and type of different parameters.someone will ask:soprintfis the Intelligent identification parameter not implemented in the?that's because the functionprintfis from the fixed parameterformatstring to parse out the type of the parameter,Call AgainVa_argto get the variable parameters..Which means,if you want to implement intelligent identification of variable parameters, you have to make judgments in your own programs ..There is also a problem,because the compiler is not strict enough to prototype a variable parameter function,bad for programming errors.

If the simple variable parameter is a char pointer, if the presence of a null pointer will produce COREDUMP

 void  simple (int   I, ...)  {  va_list arg_ptr;   char  *s= null;  va_start (arg_ptr, i);  s  =va_arg (arg_ptr, char  *);  Va_end (arg_ptr);  printf ( "  %d%s\n   " , I, s);   return  ;  }  

variable parameter is type char* , when we forget to call the function with two parameters , Core Dump (Unix) will appear or invalid page error (window platform ). but it's also possible not to make mistakes . , but mistakes are hard to find , It's not good for us to write high quality programs .

The use of variable parameters in C language

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.