C language function of the variable parameters to achieve stdarg.h

This article has reference to the understanding part
https://blog.csdn.net/u012005313/article/details/52122077

In this paper, the basis of comparison for novice, advanced To see the above article.
This article is my own understanding, if there is an error please indicate where the comments area, thank you.


First introduced header file:

#include<stdarg.h>

Require variable list of parameters to use ... instead.

For example: int add (int num, int num2, ...)


Va_list type defined in the header file stdarg.h, the parameters in the argument list.

void va_start(va_list ap, last);

↑ This function is used to initialize the object type va_list, 2 last parameter is represented by the last name of a parameter known function of the type, the last address will point AP.

The first address of the function parameter list will be read into the ap, ap fact which can be understood as a STL iterators.


type va_arg(va_list ap, type);

↑ This function is used to read the parameters from the ap, Each time, the list of parameters will be the first address ap pointer points to the next parameter
, for example: int getchar (int num, char str, char buf);
if the first ap point to char str, when executed once type va_arg (va_list ap, type) ; when, ap buf points to char;
type 2 type of the variable parameters of the function returns.


void va_end(va_list ap);

↑ This function is used to release ap memory space.

example:

#include<stdarg.h>
#include<stdio.h>
int add(int num, int num2, ...){

	int c = num;//叠加的数值  num2为 可变参数列表的参数个数


	va_list arg;

	va_start(arg,num2);

	for (int i = 0; i < num2; i++){

		
		c += va_arg(arg,int);


	}

	va_end(arg);

	return c;
	
}

void main(){

	int i = 0;

	i = add(5, 3, 5, 10, 20);

	printf("%d", i);
	
	getchar();

}

Guess you like

Origin blog.csdn.net/u013594490/article/details/93727342