c - How to find out the number of arguments (using variable arguments) if the first argument just indicates and enum value? -
so given list of enum values. function return integer value. takes in enum value , rest followed integer values. supposed total of following integer values if enum type called total , return total.
like this
#include <stdio.h> #include <stdarg.h> typedef enum rule { first, total } rule; int fund(rule rule, int v1, ...){ switch(rule){ case total: { int total = v1, value; if(v1 == -1) return 0; va_list ap; va_start(ap, v1); value = va_arg(ap, int); while(value != -1){ total += value; value = va_arg(ap, int); } va_end(ap); return total; } break; case first: return v1; } return -1; } int main(void){ printf("first:%d\n", fund(first, 1, 2, 3, 4, -1));//first:1 printf("total:%d\n", fund(total, 7, 5, 3, 1, -1));//total:16 }
Comments
Post a Comment