c - 如果第一个参数仅指示枚举值,如何找出参数的数量(使用变量参数)?

标签 c

所以我得到了一个枚举值列表。该函数将返回整数值。它接受一个枚举值,其余的后面是整数值。如果枚举类型称为总计并返回总计,我应该获得以下整数值的总和。

最佳答案

像这样

#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
}

关于c - 如果第一个参数仅指示枚举值,如何找出参数的数量(使用变量参数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317049/

相关文章:

c - 在 LCD 上显示十六进制值

c - foo->bar 和 &foo->bar 有什么区别?

c - 是什么延迟了我的 C 程序的 printf 输出?

c - C 中带有 %g 的字符串格式

不能给变量和指针赋值

c - c 中 4x4 矩阵的 getter 问题

c - 声明没有最高维度的数组

C: JSON 处理器

c - 有没有一种可移植的方法来定义 INT_MAX?

c - 在 c 中计算数组时得到错误的答案