Understanding and Using Variable Parameter va_list

Source: Internet
Author: User

Understanding and Using Variable Parameter va_list
During the C language code writing process, printf is often used to format the print. This function supports a variety of parameters and variable parameters. All variable parameters are implemented using va_list. The following is usually used: va_list vp; va_start (vp, arg1); typevalue1 = va_arg (vp, typename1 );... typevalueN = va_arg (vp, typenameN); va_end (vp );
The above is how to use variable parameters. The function defining variable parameters must have at least one definite parameter. For example, the declaration of the function printf is as follows: int printf (const char * format ,...);
Format is a required parameter; otherwise, the function compilation fails. From the code format above, we can call va_arg () multiple times to obtain the corresponding parameter value. You also need to know the corresponding value type for obtaining this value. Multiple calls to this interface also require the number of variable parameters, which must be passed in some form. Therefore, to use va_list, you must know the number of parameters and the corresponding parameter type.
These parameters are actually passed when the variable parameter interface printf is usually exposed, because a series of formats are usually set when the printf () function is called, these formats indicate the number of variable parameters and the corresponding parameter types, in this way, printf can determine the type through the formatted symbols, and the number of escape characters determines the number of variable parameters. Printf ("% d, % d \ n", a, B, c, d); the number of % d is known, the number of variable parameters is four, and % d indicates an integer. Therefore, the required type corresponds to int.
Here is a brief introduction to the va_list implementation method: in C language, the stack is a very important part. Only by understanding the composition of the stack can we understand the call process of the program, this section briefly introduces the stack form in the function call process. The basic model is as follows:

The basic model of function call is as follows. The parameter can be used to locate the corresponding parameter location through the current stack frame location, that is, the parameter value passed by the function that calls the current function can be found based on the location of Calledfunc_EBP. These parameter values are stored in the stack space. the space occupied by the parameter and the storage location of the current parameter can be used to calculate the location of other parameters. Because there must be a known definite parameter in va_list, this parameter is actually used to determine the starting position of a variable parameter. The basic principles for determining this parameter are shown in. Of course, this diagram is just a model diagram, and there may be some differences in implementation. The detailed description is not provided here.

Here is a simple method for calculating the sum of variable integer integers. The size parameter is used to save the number of parameters. Because it is an integer, va_arg directly processes the int type.

 
 
  1. #include
  2. #include
  3. #include

  4. #include

  5. int f(int x, int y, int z)
  6. {
  7. return x + y + z;
  8. }

  9. int sum(int size, ...)
  10. {
  11. va_list vp;
  12. int s = 0;
  13. int i = 0;

  14. va_start(vp, size);
  15. for (i = 0; i < size; ++ i) {
  16. s += va_arg(vp, int);
  17. }
  18. va_end(vp);

  19. printf("%d,%d\n", size, s);
  20. }

  21. int main()
  22. {
  23. int a = 1;
  24. int b = 2;
  25. int c = 3;

  26. printf("%d\n", f(a, b , c));
  27. sum(5, 20, 30, 40, 50, 20);
  28. return 0;
  29. }
There are still many usage of va_list, and there are a lot of processing in the Code related to message parsing. This example is to get the same type of data, there may be various formats in formatting, you only need to obtain parameters based on different formats to complete the processing of complex formats. For this part, refer to the redis-cli processing logic for cli, as shown below:
 
 
  1. Void * redisCommand (redisContext * c, const char * format ,...){
  2. Va_list ap;
  3. Void * reply = NULL;
  4. Va_start (ap, format); // The relative start address of a variable parameter that has been formatted.
  5. Reply = redisvCommand (c, format, ap); // process the ap
  6. Va_end (ap );
  7. Return reply;
  8. }
Next, view the ap-related operation logic:

 
 
  1. Int redisvFormatCommand (char ** target, const char * format, va_list ap ){
  2. Const char * c = format;
  3. Char * cmd = NULL;/* final command */
  4. Int pos;/* position in final command */
  5. Sds curarg, newarg;/* current argument */
  6. Int touched = 0;/* was the current argument touched? */
  7. Char ** curargv = NULL, ** newargv = NULL;
  8. Int argc = 0;
  9. Int totlen = 0;
  10. Int j;

  11. /* Abort if there is not target to set */
  12. If (target = NULL)
  13. Return-1;

  14. /* Build the command string accordingly to protocol */
  15. Curarg = sdsempty ();
  16. If (curarg = NULL)
  17. Return-1;

  18. While (* c! = '\ 0 '){
  19. If (* c! = '%' | C [1] = '\ 0 '){
  20. If (* c = ''){
  21. If (touched ){
  22. Newargv = realloc (curargv, sizeof (char *) * (argc + 1 ));
  23. If (newargv = NULL) goto err;
  24. Curargv = newargv;
  25. Curargv [argc ++] = curarg;
  26. Totlen + = bulklen (sdslen (curarg ));

  27. /* Curarg is put in argv so it can be overwritten .*/
  28. Curarg = sdsempty ();
  29. If (curarg = NULL) goto err;
  30. Touched = 0;
  31. }
  32. } Else {
  33. Newarg = sdscatlen (curarg, c, 1 );
  34. If (newarg = NULL) goto err;
  35. Curarg = newarg;
  36. Touched = 1;
  37. }
  38. } Else {
  39. Char * arg;
  40. Size_t size;

  41. /* Set newarg so it can be checked even if it is not touched .*/
  42. Newarg = curarg;

  43. Switch (c [1]) {
  44. Case's ': // string processing
  45. Arg = va_arg (ap, char *);
  46. Size = strlen (arg );
  47. If (size> 0)
  48. Newarg = sdscatlen (curarg, arg, size );
  49. Break;
  50. Case 'B ':
  51. Arg = va_arg (ap, char *); // obtain the string address first.
  52. Size = va_arg (ap, size_t); // obtain the length of the string
  53. If (size> 0)
  54. Newarg = sdscatlen (curarg, arg, size );
  55. Break;
  56. Case '% ':
  57. Newarg = sdscat (curarg, "% ");
  58. Break;
  59. Default:
  60. /* Try to detect printf format */
  61. {
  62. Static const char intfmts [] = "diouxX ";
  63. Char _ format [16];
  64. Const char * _ p = c + 1;
  65. Size_t _ l = 0;
  66. Va_list _ cpy;

  67. /* Flags */
  68. If (* _ p! = '\ 0' & * _ p =' # ') _ p ++;
  69. If (* _ p! = '\ 0' & * _ p = '0') _ p ++;
  70. If (* _ p! = '\ 0' & * _ p ='-') _ p ++;
  71. If (* _ p! = '\ 0' & * _ p = '') _ p ++;
  72. If (* _ p! = '\ 0' & * _ p =' + ') _ p ++;

  73. /* Field width */
  74. While (* _ p! = '\ 0' & isdigit (* _ p) _ p ++;

  75. /* Precision */
  76. If (* _ p = '.'){
  77. _ P ++;
  78. While (* _ p! = '\ 0' & isdigit (* _ p) _ p ++;
  79. }

  80. /* Copy va_list before consuming with va_arg */
  81. Va_copy (_ cpy, ap );

  82. /* Integer conversion (without modifiers )*/
  83. If (strchr (intfmts, * _ p )! = NULL ){
  84. Va_arg (ap, int); // obtain the Parameter
  85. Goto fmt_valid;
  86. }

  87. /* Double conversion (without modifiers )*/
  88. If (strchr ("eEfFgGaA", * _ p )! = NULL ){
  89. Va_arg (ap, double); // get floating point number
  90. Goto fmt_valid;
  91. }

  92. /* Size: char */
  93. If (_ p [0] = 'H' & _ p [1] = 'H '){
  94. _ P + = 2;
  95. If (* _ p! = '\ 0' & strchr (intfmts, * _ p )! = NULL ){
  96. Va_arg (ap, int);/* char gets promoted to int */
  97. Goto fmt_valid;
  98. }
  99. Goto fmt_invalid;
  100. }

  101. /* Size: short */
  102. If (_ p [0] = 'H '){
  103. _ P + = 1;
  104. If (* _ p! = '\ 0' & strchr (intfmts, * _ p )! = NULL ){
  105. Va_arg (ap, int);/* short gets promoted to int */
  106. Goto fmt_valid;
  107. }
  108. Goto fmt_invalid;
  109. }

  110. /* Size: long */
  111. If (_ p [0] = 'l' & _ p [1] = 'l '){
  112. _ P + = 2;
  113. If (* _ p! = '\ 0' & strchr (intfmts, * _ p )! = NULL ){
  114. Va_arg (ap, long );
  115. Goto fmt_valid;
  116. }
  117. Goto fmt_invalid;
  118. }

  119. /* Size: long */
  120. If (_ p [0] = 'l '){
  121. _ P + = 1;
  122. If (* _ p! = '\ 0' & strchr (intfmts, * _ p )! = NULL ){
  123. Va_arg (ap, long );
  124. Goto fmt_valid;
  125. }
  126. Goto fmt_invalid;
  127. }

  128. Fmt_invalid:
  129. Va_end (_ cpy );
  130. Goto err;

  131. Fmt_valid:
  132. _ L = (_ p + 1)-c;
  133. If (_ l <sizeof (_ format)-2 ){
  134. Memcpy (_ format, c, _ l );
  135. _ Format [_ l] = '\ 0 ';
  136. Newarg = sdscatvprintf (curarg, _ format, _ cpy );

  137. /* Update current position (note: outer blocks
  138. * Increment c twice so compensate here )*/
  139. C = _ P-1;
  140. }

  141. Va_end (_ cpy );
  142. Break;
  143. }
  144. }

  145. If (newarg = NULL) goto err;
  146. Curarg = newarg;

  147. Touched = 1;
  148. C ++;
  149. }
  150. C ++;
  151. }

  152. /* Add the last argument if needed */
  153. If (touched ){
  154. Newargv = realloc (curargv, sizeof (char *) * (argc + 1 ));
  155. If (newargv = NULL) goto err;
  156. Curargv = newargv;
  157. Curargv [argc ++] = curarg;
  158. Totlen + = bulklen (sdslen (curarg ));
  159. } Else {
  160. Sdsfree (curarg );
  161. }

  162. /* Clear curarg because it was put in curargv or was free 'd .*/
  163. Curarg = NULL;

  164. /* Add bytes needed to hold multi bulk count */
  165. Totlen + = 1 + intlen (argc) + 2;

  166. /* Build the command at protocol level */
  167. Cmd = malloc (totlen + 1 );
  168. If (cmd = NULL) goto err;

  169. Pos = sprintf (cmd, "* % d \ r \ n", argc );
  170. For (j = 0; j <argc; j ++ ){
  171. Pos + = sprintf (cmd + pos, "$ % zu \ r \ n", sdslen (curargv [j]);
  172. Memcpy (cmd + pos, curargv [j], sdslen (curargv [j]);
  173. Pos + = sdslen (curargv [j]);
  174. Sdsfree (curargv [j]);
  175. Cmd [pos ++] = '\ R ';
  176. Cmd [pos ++] = '\ n ';
  177. }
  178. Assert (pos = totlen );
  179. Cmd [pos] = '\ 0 ';

  180. Free (curargv );
  181. * Target = cmd;
  182. Return totlen;

  183. Err:
  184. While (argc --)
  185. Sdsfree (curargv [argc]);
  186. Free (curargv );

  187. If (curarg! = NULL)
  188. Sdsfree (curarg );

  189. /* No need to check cmd since it is the last statement that can fail,
  190. * But do it anyway to be as defensive as possible .*/
  191. If (cmd! = NULL)
  192. Free (cmd );

  193. Return-1;
  194. }
From the above Code, we actually perform repeated operations on va_list to obtain the specific content. Through va_list, you can easily solve the formatting operation.

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.