Home >Backend Development >C++ >How to Pass Variable Arguments Between C Functions with Variable Argument Lists?

How to Pass Variable Arguments Between C Functions with Variable Argument Lists?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-12 12:32:13398browse

How to Pass Variable Arguments Between C Functions with Variable Argument Lists?

How to Pass Variable Arguments between Functions with Variable Argument Lists

Problem:

You have two functions, example() and exampleB(), with similar variable argument lists:

void example(int a, int b, ...);
void exampleB(int b, ...);

You need to call example() from within exampleB() without modifying the latter's variable argument list, as it is used elsewhere.

Solution:

Unfortunately, there is no direct method to pass variable arguments in C. To achieve this, you must define a helper function that takes a va_list parameter. Here's an example:

#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...
}

In this setup:

  • exampleV() is the helper function that takes a va_list argument.
  • do_something(a) is an example of using the a argument within exampleA().
  • exampleV() is called from both exampleA() and exampleB() with the corresponding variable argument list.
  • exampleV() performs the operations originally intended for exampleB() but does not call va_start() or va_end().

By adding exampleV() as an intermediary, you can pass the variable arguments to exampleB() without modifying its original implementation.

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

Statement:
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