summaryrefslogtreecommitdiff
path: root/variable_argument_functions.c
diff options
context:
space:
mode:
authorClay Smith <claysmith158@gmail.com>2023-08-01 01:09:09 -0500
committerClay Smith <claysmith158@gmail.com>2023-08-01 01:09:09 -0500
commit102341d7ae8793c29d44fa416d3b5b797d1eca3e (patch)
tree6df9a5d5ef978dc6809a7d71d50de6e359dae2e7 /variable_argument_functions.c
First commitHEADmain
Diffstat (limited to 'variable_argument_functions.c')
-rw-r--r--variable_argument_functions.c108
1 files changed, 108 insertions, 0 deletions
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 <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;
+}