From 102341d7ae8793c29d44fa416d3b5b797d1eca3e Mon Sep 17 00:00:00 2001 From: Clay Smith Date: Tue, 1 Aug 2023 01:09:09 -0500 Subject: First commit --- variable_argument_functions.c | 108 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 variable_argument_functions.c (limited to 'variable_argument_functions.c') diff --git a/variable_argument_functions.c b/variable_argument_functions.c new file mode 100644 index 0000000..8db99df --- /dev/null +++ b/variable_argument_functions.c @@ -0,0 +1,108 @@ +#include +#include +#include + +//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; +} -- cgit v1.2.1