What is vprintf() in C?

vprintf() is a built-in function defined in the <stdio.h> header.

The following is the function prototype:

int vprintf (const char * format, va_list arg);

Functionality

vprintf() writes the input string to stdout.

The function works in a similar way to printf(). However, vprintf() uses elements in the variable argument list to replace format specifiers rather than using additional arguments.

The vprintf() function

Parameters and return

vprintf() takes two input arguments.

  • format: the string to be written to stdout. Contains format specifiers as in printf().

  • arg: a variable argument list that contains the placeholders for the format specifiers.

The vprintf() function returns the total number of characters written.

In case of an error, the function returns a negative number.

Code

#include <stdio.h>
#include <stdarg.h>
void VariadicFunction ( const char * format, ... )
{
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
}
int main ()
{
VariadicFunction("My format contains a %s\n", "string");
VariadicFunction("My format contains %d and a %s\n", 7, "string");
return 0;
}

In the above example, we begin by declaring a variadic function.

This function takes the format string and variable arguments as input parameters.

When the format string and variable arguments pass to the function, va_list is created to store the variable arguments.

va_list is defined in <stdarg.h>.

vprintf() can write the string onto stdout, replacing the format specifiers with the relevant argument from va_list.

Copyright ©2024 Educative, Inc. All rights reserved