Functions receiving a variable number of arguments
To conclude our introduction to functions and parameter passing,
we consider functions such as printf() which may receive
a variable number of arguments!
We've carefully introduced the concepts that functions receive
strongly typed parameters,
that a fixed number of function arguments
in the call are bound to the parameters, and
that parameters are then considered as local variables.
But, consider the perfectly legal code:
#include <stdio.h>
int i = 238;
float x = 1.6;
printf("i is %i, x is %f\n", i, x);
....
printf("this function call only has a single argument\n");
....
printf("x is %f, i is %i, and x is still %f\n", x, i, x);
|
In these cases, the first argument is always a string,
but the number and datatype of the provided arguments keeps changing.
printf() is one of a small set of standard functions that permits
this apparent inconsistency.
It should be clear that the format specifiers of the first argument
direct the expected type and number of the following arguments.
Fortunately,
within the ISO-C11 specification,
our cc compiler is permitted to check our format strings,
and warn us (at compile time)
if the specifiers and arguments don't "match".
prompt> cc -o try try.c
try.c:9:20: warning: format specifies type 'int' but the argument has type 'char *'
[-Wformat]
printf("%i\n", "hello");
~~ ^~~~~~~
%s
1 warning generated.
|
CITS2002 Systems Programming, Lecture 4, p11, 31st July 2024.
|