Created
December 1, 2021 23:46
-
-
Save 3imed-jaberi/eeb49a12859cd40b684d90fcaf346c68 to your computer and use it in GitHub Desktop.
Variadic functions in C lang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ########################### // | |
| // # 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