summaryrefslogtreecommitdiff
path: root/variable_argument_functions.c
blob: 8db99df1e4b064f5334652896ded4ae236458a6c (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

//Function Prototypes
double add(int num_args, ...);
void printArray(int num_args, char** types, ...);

int main(void)
{
	int v = 6, w = 3, x = 1, y = 4, z = 2;
	double sum;

	sum = add(5,v,w,x,y,z);

	printf("main function end: %lf\n",sum);

	printf("%d\n",22,v+1);
	//I included the above printf to show that this code is valid and will compile.
	//While this code does give warnings, there is no error and the program runs as if the 23 was not there. 
	//the expression still occur, but the printf does nothing else with them

	char a = 'a';
	short b = 69;
	int c = 7;
	long d = 3009;
	long long e = 4567889;
	float f = 3.1;
	double g = 6.402;

	char* array1[11] = {
		"char",
		"short",
		"int",
		"long",
		"long long",
		"float",
		"double"
	};

	printf("%c, %hu, %d, %ld, %lld, %f, %lf\n",a,b,c,d,e,f,g);

	printArray(7, array1, a, b, c, d, e, f, g);


	return 0;
}

void printArray(int num_args, char** types,...)
{
	va_list list_of_args;
	va_start(list_of_args, types);

	for (int i = 0; i < num_args; ++i) {

		if (!strcmp(types[i], "int")) {
			printf("INTEGER: %d", va_arg(list_of_args, int));


		} else if (!strcmp(types[i], "long long")) {
			printf("LONG: %lld", va_arg(list_of_args, long long));


		} else if (!strcmp(types[i], "long")) {
			printf("LONG LONG: %ld", va_arg(list_of_args, long));


		} else if (!strcmp(types[i], "short")) {
			printf("SHORT: %d", va_arg(list_of_args, int));


		} else if (!strcmp(types[i], "char")) {
			printf("CHAR: %c", va_arg(list_of_args, int));


		} else if (!strcmp(types[i], "float")) {
			printf("FLOAT: %lf", va_arg(list_of_args, double));


		} else if (!strcmp(types[i], "double")) {
			printf("DOUBLE: %lf", va_arg(list_of_args, double));


		} else {
			fprintf(stderr,"ERROR");
		}
		printf("\n");
	}
	va_end(list_of_args);
}

double add(int num_args, ...)
{
	va_list my_list;

	double i = 0, sum = 0;

	va_start(my_list, num_args);
	

	for (i = 0; i < num_args; ++i) {
		printf("%lf\n",sum += va_arg(my_list, int));
	}

	va_end(my_list);

	return sum;
}