Variable argument list for C-language functions

Source: Internet
Author: User
Tags function prototype

Variable parameter lists can be implemented with macros defined in the Stdarg.h header file, which is part of the standard library. This header file declares a type va_list and three macros----Va_start,va_arg,va_end. You can declare a variable of type va_list, used with these macros, to access the value of the parameter. The variable portion of a parameter list is located after one or more common parameters (named arguments), which is at least one named parameter in the parameter list, and is represented by an ellipsis in the function prototype.

For example: Define a function average can calculate the average of several integers:

1#include <stdarg.h>2 floatAverageintn_value,...)3 {4 va_list Var_arg;5     intcount;6     floatsum=0;7 8 Va_start (var_arg,n_value);9 Ten      for(Count =0; count<n_value;count++) One     { ASum+=va_arg (Var_arg,int); -     } -  the va_end (var_arg); -     returnsum/n_values; -}

Description: The function declares a variable called Va_arg, which is used to access an indeterminate part of the parameter list. This variable is initialized by calling Va_start. Its first argument is the name of the va_list type variable, and the second argument is the last named argument before the ellipsis. The initialization process sets the variable VAR_ARG to the first parameter that points to the variable parameter section. To access the parameters, you need to use VA_ARG, which accepts two parameters: thetype of the va_list type variable and the next parameter in the argument list. In this example, all of the mutable parameters are integral types. Va_arg returns the value of this parameter and causes Var_arg to point to the next mutable parameter. Finally, you need to call Va_end after the last mutable parameter has been accessed.

Variable argument list for C-language functions

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.