Skip to content

Instantly share code, notes, and snippets.

@3imed-jaberi
Created December 1, 2021 23:46
Show Gist options
  • Select an option

  • Save 3imed-jaberi/eeb49a12859cd40b684d90fcaf346c68 to your computer and use it in GitHub Desktop.

Select an option

Save 3imed-jaberi/eeb49a12859cd40b684d90fcaf346c68 to your computer and use it in GitHub Desktop.
Variadic functions in C lang
// ########################### //
// # Variadic functions in C # //
// ########################### //
/**
* Variadic functions are functions that can take a variable number of arguments.
* It's like spread op. all arguments in function signature in JavaScript.
*/
// ################################################################################# //
/**
* <stdarg.h> includes the following methods:
* - va_start(va_list ap, argN): This enables access to variadic function arguments.
* - va_arg(va_list ap, type): This one accesses the next variadic function argument.
* - va_copy(va_list dest, va_list src): This makes a copy of the variadic function arguments.
* - va_end(va_list ap): This ends the traversal of the variadic function arguments.
*/
#include <stdarg.h>
#include <stdio.h>
/**
* The following simple C program will demonstrate the working of the variadic function addNumbers():
*/
// variadic function to add numbers //
int addNumbers(int n, ...) {
int Sum = 0;
// declaring pointer to the argument list
va_list ptr;
// initializing argument to the list pointer
va_start(ptr, n);
for (int i = 0; i < n; i++)
// accessing current variable and pointing to next one
Sum += va_arg(ptr, int);
// ending argument list traversal
va_end(ptr);
return Sum;
}
// main code
int main() {
printf("\n\n variadic functions: \n");
// variable number of arguments
printf("\n 1 + 2 = %d ", addNumbers(2, 1, 2));
printf("\n 3 + 4 + 5 = %d ", addNumbers(3, 3, 4, 5));
printf("\n 6 + 7 + 8 + 9 = %d ", addNumbers(4, 6, 7, 8, 9));
printf("\n");
return 0;
}
/**
* Output:
* variadic functions:
*
* 1 + 2 = 3
* 3 + 4 + 5 = 12
* 6 + 7 + 8 + 9 = 30
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment