Talking about Variable Parameters in C Language

1. Reasons for variable parameters

Let's start with a simple example.

int Add(int x, int y)
{
    return x + y;
}
int main()
{
    int sum = 0;
    sum = Add(1, 2);
    //sum = Add(1, 2, 3);
    //sum = Add(1);
    system("pause");
    return 0;
}

We can see that for this code only the addition of two numbers can be calculated.
In this way we introduce a new knowledge point!

Variable parameter implementation to find the sum of any number

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

int Add(int num, ...)
{
    int sum = 0;
    va_list arg;
    va_start(arg, num);

    for (int i = 0; i < num; i++)
    {
        sum += va_arg(arg, int);
    }

    va_end(arg);
    return sum;
}
int main()
{
    printf("%d\n", Add(4, 2, 3, 4, 5));
    system("pause");
    return 0;
}

Detailed explanation

1. The first sentence of the main() function
printf("%d\n", Add(4,     2, 3, 4, 5));

The first 4 indicates the number of elements and the remaining indicates the content of the element

2.

The meaning of the operator:

1.

    va_list arg;
macro operator actual meaning Detailed explanation
va_list char * va_list arg Creates a character pointer arg for accessing the undetermined portion of the argument list.

2.

    va_start(arg, num);

(ap=(va_list)&v + _INTSIZEOF(v))

macro operator actual meaning Detailed explanation
va_start (ap,v) (ap=(va_list)&v + _INTSIZEOF(v)) Initialize the variable arg, va_start has two parameters, its first parameter is the character pointer created by va_list. The second parameter is the parameter before "..."; (the ellipsis cannot be read)
va_start (arg, num) (arg=(char *)&v + _INTSIZEOF(num))
_INTSIZEOF (sizeof(n) + sizeof(int)-1 & ~(sizeof(int)-1) Skip num and go to the first argument of positional arguments. round up to an integer multiple of four

3.

    for (int i = 0; i < num; i++)
    {
        sum += va_arg(arg, int);
    }
macro operator actual meaning Detailed explanation
va_arg(ap,t) (* (t *) ((ap + = _INTSIZEOF (t)) - _INTSIZEOF (t))) (*(t*)((arg += _INTSIZEOF(int)) - _INTSIZEOF(int)))
(*(t*)((arg += _INTSIZEOF(int)) - _INTSIZEOF(int))) (* (int *) ((arg + = 4) - 4))
(arg += 4) - 4) angry; arg + = 4; First add 4 to arg and then subtract it. The result of arg is unchanged this time, but arg points to the next position. One code does two actions
    for (int i = 0; i < num; i++)
    {
        sum += va_arg(arg, int);
    }

Take out all unknown parameters and add them to sum

macro operator actual meaning Detailed explanation
va_end(ap) (ap = (va_list) 0) Assign a null pointer to a pointer. release when not in use
va_end(arg);

The pointer must be released when it is used up to prevent random pointers.

Guess you like

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