Home > Backend Development > C++ > How to Pass Variable Arguments from One Function to Another with Variable Argument Lists?

How to Pass Variable Arguments from One Function to Another with Variable Argument Lists?

Mary-Kate Olsen
Release: 2024-12-07 03:18:10
Original
844 people have browsed it

How to Pass Variable Arguments from One Function to Another with Variable Argument Lists?

Passing Variable Arguments to Functions with Variable Argument Lists

When working with functions that accept a variable number of arguments, it's often necessary to call one such function from another. However, directly passing arguments from one function to another can be problematic without modifying the target function if it's already in use elsewhere.

Consider the following example:

void example(int a, int b, ...);
void exampleB(int b, ...);
Copy after login

In this scenario, example calls exampleB. However, the question arises: how can the variable arguments in example be passed to exampleB without modifying its original implementation?

Directly passing arguments from example to exampleB is not possible. Instead, an intermediary function that takes a va_list must be created:

#include <stdarg.h>

static void exampleV(int b, va_list args);

void exampleA(int a, int b, ...)    // Renamed for consistency
{
    va_list args;
    do_something(a);                // Use argument a somehow
    va_start(args, b);
    exampleV(b, args);
    va_end(args);
}

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}
Copy after login

By introducing exampleV, which takes both b and args as arguments, exampleA can pass its variable arguments to exampleB without modifying its implementation. This intermediary function can then be used to perform the intended actions without disrupting the original implementation of exampleB.

The above is the detailed content of How to Pass Variable Arguments from One Function to Another with Variable Argument Lists?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template