Variadic functions accept a variable number of arguments. Common examples include printf(), scanf(), and sum(). They provide flexibility when you don’t know in advance how many arguments will be passed.
Think of printf(): you can call it with one format specifier or many:
#include "variadic_functions.h"#include <stdarg.h>/** * sum_them_all - function that returns the sum of all its parameters * @n: number of arguments * Return: sum of all arguments * if n==0, return 0 */int sum_them_all(const unsigned int n, ...){ int sum = 0; unsigned int i; va_list lptr; va_start(lptr, n); for (i = 0; i < n; i++) sum += va_arg(lptr, int); va_end(lptr); return (sum);}
Breaking it down:
Function signature:int sum_them_all(const unsigned int n, ...)
n is the count of remaining arguments (fixed parameter)
#include "variadic_functions.h"#include <stdarg.h>#include <stdio.h>/** * print_numbers - function that prints numbers, followed by a new line * @separator: string to be printed between numbers * @n: number of integers passed to the function * Return: null */void print_numbers(const char *separator, const unsigned int n, ...){ va_list valist; unsigned int i; va_start(valist, n); for (i = 0; i < n; i++) { printf("%d", va_arg(valist, int)); if (separator != NULL && i < n - 1) printf("%s", separator); } printf("\n"); va_end(valist);}
Key features:
Takes a separator string (can be NULL)
Prints separator between numbers (but not after the last one)
#include "variadic_functions.h"#include <stdio.h>#include <stdarg.h>/** * print_strings - function that prints strings, followed by a new line * @separator: string to be printed between each string * @n: number of strings passed to the function * Retrun: null */void print_strings(const char *separator, const unsigned int n, ...){ va_list valist; unsigned int i; char *str; va_start(valist, n); for (i = 0; i < n; i++) { str = va_arg(valist, char *); if (str == NULL) printf("(nil)"); else printf("%s", str); if (separator != NULL && i < n - 1) printf("%s", separator); } printf("\n"); va_end(valist);}
Important safety check:
if (str == NULL) printf("(nil)");
Always check if string pointers are NULL before using them! Attempting to print a NULL string with %s causes undefined behavior.
int sum_until_zero(...){ va_list args; va_start(args, ???); // Problem: need last fixed param int num; int sum = 0; while ((num = va_arg(args, int)) != 0) sum += num; va_end(args); return sum;}
Problem:va_start requires at least one fixed parameter before .... Pure sentinel-based approaches need at least one fixed argument.
/** * print_all - prints various types * @format: string with type specifiers: * 'c' - char * 'i' - int * 'f' - float (passed as double) * 's' - string (char *) */
Provide fixed parameter count or format
// Good: count providedsum_them_all(5, 1, 2, 3, 4, 5);// Good: format describes argsprint_all("si", "Answer:", 42);// Bad: no way to know when to stopmystery_function(1, 2, 3); // How many args?