Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
/*
Our own little printf
foo("sdfc", string, int, float, character);
*/
void foo(const char *format, ...) {
va_list ap;
char *s;
int d;
float f;
char c;
// Tell the variable argument list where to start
// Give it the address of the last argument we know we will see
va_start(ap, format);
while (*format) {
switch (*format++) {
case 's':
// Using any type here would return the right thing
// But would mess up the metadata for the next thing
// If the size is different
s = va_arg(ap, char *);
printf("string: %s\n", s);
break;
case 'f':
// Doesn't work: floats always promoted to doubles through va list
// chars and shorts promoted to int
//f = va_arg(ap, float);
f = va_arg(ap, double);
printf("floating point num: %f\n", f);
break;
case 'd':
d = va_arg(ap, int);
printf("integer: %d\n", d);
break;
case 'c':
c = va_arg(ap, int);
printf("character: %c\n", c);
break;
}
}
va_end(ap);
}
int main(char argc, char *argv[]) {
foo("cdsfcsfd", 'a', 10, "Hello, World!", 0.0001, '3', "Goodbye!", 0.221, 42);
}