Skip to content
Snippets Groups Projects
variable_args.c 1.13 KiB
Newer Older
Jake Feddersen's avatar
Jake Feddersen committed
#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);
}