This program demonstrates a variadic function, myPrintFunc
, that can handle a variable number of arguments of different types. The function uses a format string to specify the types of the arguments and processes them accordingly, printing integers and floating-point numbers to the console.
#include <stdio.h> #include <stdarg.h> #include <string.h> void myPrintFunc(char* types, ...); int main(){ myPrintFunc("FDFDF", 2.4, 3, 4.6, 9, 23.1); return 0; } void myPrintFunc(char* types, ...){ int num_args = strlen(types); va_list args; va_start(args, types); for (int i=0; i<num_args; i++){ if (types[i] == 'D'){ int x = va_arg(args, int); printf("%d\n", x); } else if (types[i] == 'F'){ double x = va_arg(args, double); printf("%.1f\n", x); } } va_end(args); }
Code Explanation
1. Header Files
#include <stdio.h>
: Provides theprintf()
function for output.#include <stdarg.h>
: Provides macros for handling variadic arguments (va_list
,va_start
,va_arg
, andva_end
).#include <string.h>
: Provides thestrlen()
function to calculate the length of the type string.
2. Main Function
- calls
myPrintFunc
with a format string"FDFDF"
and corresponding arguments:2.4
,3
,4.6
,9
, and23.1
. - the format string specifies the types of the arguments:
'F'
for floating-point numbers (double in C).'D'
for integers.
- the function processes and prints these arguments based on the format string.
3. Variadic Function
- definition:
void myPrintFunc(char* types, ...)
:- the first parameter,
types
, is a format string specifying the types of the following arguments. - the
...
syntax indicates a variable number of additional arguments.
- the first parameter,
- implementation:
- the length of the format string is determined using
strlen(types)
. - a
va_list
is initialized withva_start(args, types)
. - A loop iterates through the format string, and for each character:
'D'
: Fetches an integer usingva_arg(args, int)
and prints it with%d
.'F'
: Fetches a double usingva_arg(args, double)
and prints it with%.1f
.
va_end(args)
is called to clean up theva_list
.
- the length of the format string is determined using
4. Output
2.4 3 4.6 9 23.1
Conclusion
This program showcases how to implement a versatile variadic function capable of handling different data types based on a format string. This approach is foundational in C programming and is used in standard functions like printf()
and scanf()
. It is crucial for scenarios where the number and types of arguments vary at runtime, enabling flexible and reusable code. However, developers must carefully manage the format string and arguments to ensure type safety and avoid undefined behavior. This concept is especially important in developing custom logging, debugging, or utility functions.