How to implement variable parameters in C language

Source: Internet
Author: User

There are many functions in the C-language library that are similar to PRINTF,SCANF, and the number of arguments received by these functions is indeterminate. These functions are actually implemented through the Va_list,va_start,va_arg,va_end macro definition in the <stdarg.h> file. In addition, when we know the memory structure of the program runtime, we can also get the actual parameter values by directly accessing these memory spaces (in fact, the relevant macro definitions in the Stdarg.h file are doing so).

#include <stdio.h> #include <stdlib.h> #include <stdarg.h>int sum1 (int nums); int sum2 (int nums); int Main () {int result1 = 0;int Result2 = 0;RESULT1 = Sum1 (5, 1, 2, 3, 4, 5); result2 = sum2 (5, 1, 2, 3, 4, 5);p rintf ("Result1 I S%d\n ", RESULT1);p rintf (" Result2 is%d\n ", result2); System (" pause "); Stack is from high address to low address growth, C language function parameter is from right to left into the stack//c language in the stack is determined by the function caller (_ccall)//c++ in the stack is the function itself (_stdcall), C + + also support variable parameters,// But needs to be declared as int sum1 (int nums,...) form int sum1 (int nums) {int result = 0;int *argptr = &nums;//Get the address of the parameter nums for (int i = 0; i < nums; i++) Result + = * (++ar GPTR); return result;} Use the VA_LIST,VA_START,VA_END,VA_ARG macro definition in <stdarg.h> to implement int sum2 (int nums) {int result = 0;va_list Argptr;va_start ( Argptr,nums); for (int i = 0; i < nums; i++) result + = Va_arg (argptr, int); Va_end (argptr); return result;}

The program runs the following results



How to implement 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.