A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.cppreference.com/w/cpp/algorithm/../algorithm/../../cpp/../c/header/../variadic.html below:

Variadic functions - cppreference.com

Variadic functions are functions (e.g. printf) which take a variable number of arguments.

The declaration of a variadic function uses an ellipsis as the last parameter, e.g. int printf(const char* format, ...);. See variadic arguments for additional detail on the syntax and automatic argument conversions.

Accessing the variadic arguments from the function body uses the following library facilities:

Types holds the information needed by va_start, va_arg, va_end, and va_copy
(typedef) [edit] Macros enables access to variadic function arguments
(function macro) [edit] accesses the next variadic function argument
(function macro) [edit] makes a copy of the variadic function arguments
(function macro) [edit] ends traversal of the variadic function arguments
(function macro) [edit] [edit] Example

Print values of different types.

#include <stdarg.h>
#include <stdio.h>
 
void simple_printf(const char* fmt, ...)
{
    va_list args;
 
    for (va_start(args, fmt); *fmt != '\0'; ++fmt)
    {
        switch(*fmt)
        {
            case 'd':
            {
                int i = va_arg(args, int);
                printf("%d\n", i);
                break;
            }
            case 'c':
            {
                // A 'char' variable will be promoted to 'int'
                // A character literal in C is already 'int' by itself
                int c = va_arg(args, int);
                printf("%c\n", c);
                break;
            }
            case 'f':
            {
                double d = va_arg(args, double);
                printf("%f\n", d);
                break;
            }
            default:
                puts("Unknown formatter!");
                goto END;
        }
    }
END:
    va_end(args);
}
 
int main(void)
{
    simple_printf("dcff", 3, 'a', 1.969, 42.5);
}

Output:

[edit] References
[edit] See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4