Reputation: 190
In function with variable number of arguments, the "first argument" is "total number of arguments" being passed. But in printf()
we never mention argument count. So how does it get to know about the total argument list ? How does printf()
works ?
Upvotes: 2
Views: 325
Reputation: 123468
Conversion specifiers in the format string tell printf
the number and types of arguments it should expect - for example, the format string "there are %d vowels in %s\n"
tells printf
to expect two arguments in addition to the format string, the first one being type int
and the second being char *
.
It's up to you to make sure the arguments match up with the format string. If you don't pass enough arguments, or the argument types don't match what the format string expects, then the behavior is undefined (most likely garbled output or a runtime error). If you pass too many arguments, the additional arguments are evaluated, but otherwise the function will operate normally as long as the format string is satisfied.
Edit
7.21.6.1 Thefprintf
function
...
2 Thefprintf
function writes output to the stream pointed to bystream
, under control of the string pointed to byformat
that specifies how subsequent arguments are converted for output. 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. The fprintf function returns when the end of the format string is encountered.
Upvotes: 1
Reputation: 745
Let's look on printf
declaration structure:
int printf(const char *format, ...)
format
is actually the string that contains the text to be written to stdout
.
The contained embedded format tags are later replaced by the values specified in subsequent additional arguments, and format is set accordingly as required.
Upvotes: 3
Reputation: 6063
You don't supply an argument count to printf
- You do supply a format string, however - And that specifies how many arguments printf
should expect.
Very roughly speaking, the number of %
signs in the format string is the argument count (although reality is a bit more complicated).
Upvotes: 3