c - “Typesafe”枚举以避免检查 C 中的数组索引

标签 c arrays

使用“类型安全”枚举来限制函数参数以避免检查数组索引越界是否合适?

我有一个模块,它将其实例的数据保存在数组中。应使用索引从模块外部访问实例的数据。将有几个接口(interface)函数,我想避免几个 if 语句。

以下示例:

// In myInstanceModule.h

typedef struct { enum { FIRST, SECOND } index_e; } instance_tst;
#define FIRST_INSTANCE  (instance_tst){ FIRST }
#define SECOND_INSTANCE (instance_tst){ SECOND }

void instance_init_v();
void instance_print_v(instance_tst instance);

// In myInstanceModule.c

#define MEMBER_COUNT 2

typedef struct myArray {
    int myValue; 
}myArray_tst;

static myArray_tst myMembers_ast[MEMBER_COUNT];

void instance_init_v() {
    for (int i = 0; i < MEMBER_COUNT; i++)
    {
        myMembers_ast[i].myValue = i * 10;
    }
}

void instance_print_v(instance_tst instance) {
    printf("Value of this instance is: %d \n", myMembers_ast[instance.index_e].myValue);
}

// In main.c

#include myModule.h
int main(void)
{
    int test = 1234;
    instance_init_v();

    instance_print_v(FIRST_INSTANCE);       // ok
    instance_print_v(SECOND_INSTANCE);      // ok
    //instance_print_v((instance_tst)2);    // does not compile
    //instance_print_v(test);               // does not compile
    //instance_print_v(1);                  // does not compile
    //instance_print_v(NULL);               // does not compile
}

一个文件中的示例:https://repl.it/repls/QuarrelsomeDotingComputation

最佳答案

这种方法不会阻止某人使用复合文字,例如

instance_print_v(((instance_tst){2}));

所以宁愿有

void instance_print_v(size_t index){
    if(index < sizeof(myMembers_ast)/sizeof(myMembers_ast[0]))
    {
      printf("Value of this instance is: %d \n", myMembers_ast[index].myValue);
    }
    else
    {
      printf("Value of this instance is: undefined");
    }
}

关于c - “Typesafe”枚举以避免检查 C 中的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51096245/

相关文章:

C编程退出不工作

c - 为什么这个变量等于一个数字和一个字符?

c - 使用 fgets() 接收句子输入

php - 自动添加指向关键字字符串的链接

javascript - $.each 的使用有问题吗?

arrays - MongoDB $addToSet 替换

C 函数在几次迭代后停止

c - 如何解密在 crypt() 中生成的密码?

Python访问C共享对象

javascript - jquery如何返回被选元素的数组