Home > Backend Development > C++ > How Can I Pass Variable Arguments from One Function to Another Without Modifying the Receiving Function?

How Can I Pass Variable Arguments from One Function to Another Without Modifying the Receiving Function?

DDD
Release: 2024-12-18 01:03:15
Original
462 people have browsed it

How Can I Pass Variable Arguments from One Function to Another Without Modifying the Receiving Function?

Passing Variable Arguments to Functions with Variable Argument Lists

Consider two functions with similar variable arguments:

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

Suppose example calls exampleB, but without modifying exampleB (which is used elsewhere). How can we pass the variable arguments from example to exampleB?

Solution:

Directly passing arguments is not possible. Instead, we create a wrapper function that takes a va_list:

#include <stdarg.h>
static void exampleV(int b, va_list args);
Copy after login

Modified Function exampleA:

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);
}
Copy after login

Unmodified Function exampleB:

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

Wrapper Function exampleV:

static void exampleV(int b, va_list args)
{
    // Whatever `exampleB` was intended to do...
    // Except it doesn't call either `va_start` or `va_end`.
}
Copy after login

This approach allows us to pass the variable arguments from example to exampleB without modifying the latter. The wrapper function exampleV does not call va_start or va_end, which ensures consistency with the existing usage of exampleB.

The above is the detailed content of How Can I Pass Variable Arguments from One Function to Another Without Modifying the Receiving Function?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template