C Language Learning 020: Variable Parameter functions, language learning 020

Source: Internet
Author: User

C Language Learning 020: Variable Parameter functions, language learning 020

As the name suggests, a variable parameter function is a variable parameter function, that is, the number of parameters of a function is uncertain. For example, if the getnumbertotal () method is used, we can pass a parameter, you can also pass 5 or 6 parameters.

1 # include <stdio. h> 2 # include <stdarg. h> // header file 3 4 int getnumbertotal (int args,...) required for variable parameters ,...) {// variable parameters should be placed behind the regular parameters (args ;... it indicates that there are many parameters 5 va_list l; // other parameters 6 va_start (l, args) used to save the passed to function; // It indicates the start of a variable parameter, 7 int I; 8 int total = 0; 9 // read variable parameters one by one 10 for (I = 0; I <args; I ++) {11 total + = va_arg (l, int); 12} 13 va_end (l); // destroy va_list14 return total; 15} 16 17 int main () {18 int result = getnumbertotal (,); 19 printf ("total: % I \ n", result); 20 result = getnumbertotal (, 9 ); 21 printf ("total: % I \ n", result); 22 result = getnumbertotal (5, 11, 9, 5, 13, 7); 23 printf ("total: % I \ n ", result); 24 return 0; 25}

When using variable parameters, you must note that a common parameter must be included.

We can pass a NULL value to the va_start () method, but we need to know the number of variable parameters through the first parameter.

Va_arg must be of the corresponding type when obtaining variable parameters; otherwise, an unpredictable error may occur.

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.