C Language Fundamentals: Indefinite Parameters

        In this section we will learn another important mechanism in C language, indefinite parameters. An indeterminate parameter means that a function can receive an indeterminate number of parameters. An indefinite parameter is represented by ..., which must be written after the normal parameter table, such as the well-known printf function:

int printf (char *fmt, ...);

        The first parameter of printf is char* fmt, followed by indefinite parameters. It means that it can receive any number of parameters. We can pass any number of arguments to such a function when we call it, for example:

printf("%d %d\n", 1, 2);
printf("%f %f %f\n", 1.2, 2.3, 3.4);
printf("%d %f %c %s\n", 1, 2.3, 'A', "Hello World!");

        Then, we can't help but ask, how to determine the formal parameters in the function body when a function with indefinite parameters is defined? How to get the value of the incoming parameter?

        The C language provides a way to obtain indefinite parameters, that is, use std_arg

        Let's take a look at an example of the use of std_arg:

#include <stdio.h>
#include <stdarg.h>

int sum(int first, ...)
{
	va_list arg_list;
	int sum = first;
	va_start(arg_list, first);
	int var2 = va_arg (arg_list, int);
	int var3 = va_arg (arg_list, int);
	int var4 = va_arg (arg_list, int);
	int var5 = va_arg (arg_list, int);
	sum += var2;
	sum += var3;
	sum += var4;
	sum += var5;
	va_end (arg_list);
	return sum;
}

int main(int argc, char *argv[])
{
	printf("%d\n", sum(1, 2, 3, 4, 5));
	return 0;
}

        First, we'll use #include <stdarg.h> to include this header file with negated arguments. Then define a variable of type int, we need to use va_start to pass the first parameter of the function to arg_list, so that it will know the indefinite parameters after it. Next, use va_arg to get the second parameter value, which needs to be coerced into a variable of the specified type when getting the value. Here we think that the types of the parameters are all int, and generally speaking, we can use the first parameter as the type definition of the subsequent indefinite parameters to printf, and determine the subsequent indefinite parameters by analyzing the type in the fmt string. type. Next, we obtain the third parameter, the fourth parameter and the fifth parameter through va_arg. Finally, use va_end to end the use of indefinite parameters.

        Of course, we must know all the parameter types of the function when defining the function and calling the function, otherwise the arglist will not work properly.

        Readers who are interested in the principle of arglist, please refer to "Function Stack Frame" .


Welcome to the public account: programming aliens

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691228&siteId=291194637