How to use variadic function to get max of a set of numbers in C

1 Answer

0 votes
#include <stdio.h>          
#include <stdarg.h>

// int function_name(data_type variable_name, ...);

int max(int total, ...) {
	va_list ptr;

	va_start(ptr, total);

	int max = va_arg(ptr, int);

	for (int i = 0; i < total - 1; i++) {
		int temp = va_arg(ptr, int);
		max = temp > max ? temp : max;
	}

	va_end(ptr);

	return max;
}

int main() {
	printf("%d\n", max(6, 4, 8, 2, 7, 9, 0));

	printf("%d\n", max(3, 45, 100, 99));

	return 0;
}



/*
run:
 
9
100
 
*/

 



answered Dec 7, 2022 by avibootz

Related questions

...