How does printf handle its arguments? I know that in C# I can use params
keyword to do something similar but I can't get it done in C ?
The printf function uses its first argument to determine how many arguments will follow and of what types they are. If you don't use enough arguments or if they are of the wrong type than printf will get confuses, with as a result wrong answers.
The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.
printf is a "variadic" function. This means that the argument list is declared with ... on the end, and in the implementation of printf the va_list , va_start , va_arg etc macros are used to extract the arguments from the variable length list.
Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken. Inside the function, we take the pointer of the first argument. We can get the next argument by incrementing the pointer value.
Such a function is called a variadic function. You may declare one in C using ...
, like so:
int f(int, ... );
You may then use va_start
, va_arg
, and va_end
to work with the argument list. Here is an example:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
void f(void);
main(){
f();
}
int maxof(int n_args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n_args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n",maxof(3, i, j[42], 0));
}
For more information, please see The C Book and stdarg.h.
This feature is called Variable numbers of arguments in a function. You have to include stdarg.h header file; then use va_list type and va_start, va_arg, and va_end functions within the body of your function:
void print_arguments(int number_of_arguments, ...)
{
va_list list;
va_start(list, number_of_arguments);
printf("I am first element of the list: %d \n", va_arg(list, int));
printf("I am second element of the list: %d \n", va_arg(list, int));
printf("I am third element of the list: %d \n", va_arg(list, int));
va_end(list);
}
Then call your function like this:
print_arguments(3,1,2,3);
which will print out following:
I am first element of the list: 1
I am second element of the list: 2
I am third element of the list: 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With