Home >Backend Development >C++ >How to Pass a Variable Number of Arguments to printf/sprintf in C and C ?

How to Pass a Variable Number of Arguments to printf/sprintf in C and C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 17:09:11769browse

How to Pass a Variable Number of Arguments to printf/sprintf in C and C  ?

Passing Variable Arguments to Printf/Sprintf

In C and C , the printf and sprintf functions are used for formatted printing and writing. These functions allow for the specification of a format string that controls how subsequent arguments are printed. However, there may be instances where the number of arguments to be printed is not known in advance. This raises the question of how to pass a variable number of arguments to these functions.

Solution Using vfprintf

The standard C library provides the vfprintf function, which can handle a variable number of arguments. It takes two mandatory arguments:

  • format: A pointer to the format string.
  • argptr: A va_list that holds the variable arguments.

The following code snippet demonstrates how to use vfprintf:

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

In this example, the Error function takes a format string as the first argument and an arbitrary number of additional arguments. These arguments are accessed through the va_list, which is initialized using va_start. The vfprintf function is then called with the format string and the va_list. Finally, va_end is used to clean up the va_list.

The above is the detailed content of How to Pass a Variable Number of Arguments to printf/sprintf in C and C ?. 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