Reputation: 37
What is the function definition of the printf()
function as defined in the standard C library?
I need the definition to solve the following question:
Give the output of the following:
int main() { int a = 2; int b = 5; int c = 10; printf("%d ",a,b,c); return 0; }
Upvotes: 3
Views: 33723
Reputation: 935
man 3 printf
gives...
int printf(const char *restrict format, ...);
Upvotes: 1
Reputation: 1
printf("%d ",a,b,c);
For every %(something)
you need add one referining variable, therefore
printf("%d ",a+b+c); //would work (a+b+c), best case with (int) before that
printf("%d %d %d",a,b,c); //would print all 3 integers.
Upvotes: 0
Reputation: 61910
Its
int printf(const char *format, ...);
format
is a pointer to the format string
...
is the ellipsis operator , with which you can pass variable number of arguments, which depends on how many place holders we have in the format string.
Return value is the number of characters that were printed
Have a look here about the ellipsis operator: http://bobobobo.wordpress.com/2008/01/28/how-to-use-variable-argument-lists-va_list/
Upvotes: 1
Reputation: 490143
You pass an array of chars (or pointer) as the first argument (which includes format placeholders) and additional arguments to be substituted into the string.
The output for your example would be 2
1 to the standard output. %d
is the placeholder for a signed decimal integer. The extra space will be taken literally as it is not a valid placeholder. a
is passed as the first placeholder argument, and it has been assigned 2
. The extra arguments won't be examined (see below).
printf()
is a variadic function and only knows its number of additional arguments by counting the placeholders in the first argument.
1 Markdown does not allow trailing spaces in inline code examples. I had to use an alternate space, but the space you will see will be a normal one (ASCII 0x20).
Upvotes: 4
Reputation: 400156
The C language standard declares printf
as follows:
int printf(const char *format, ...);
It returns an integer and takes a first parameter of a pointer to a constant character and an arbitrary number of subsequent parameters of arbitrary type.
If you happen to pass in more parameters than are required by the format string you pass in, then the extra parameters are ignored (though they are still evaluated). From the C89 standard §4.9.6.1:
If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.
Upvotes: 12
Reputation: 3415
Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.
%d = Signed decimal integer
Upvotes: 0