Is it a suitable approach to restrict the parameters of function with a 'typesafe' enum to avoid the check for array index out of bounds?
I have a module which holds the data of its instances in an Array. The data of an instance should be accessed from outside the module with an index. There will be several interface functions and i would like to avoid several if-statements.
Following example:
// 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
}
The example in one file: https://repl.it/repls/QuarrelsomeDotingComputation
instance_print_v((instance_tst){20});