enum FieldTypes
{
FIELD_X,
FIELD_Y,
FIELD_Z
};
int main(void)
{
struct my_array_t arrayofstructs[200];
somefunction(arrayofstructs,FIELD_X);
return 0;
}
void somefunction(struct my_array_t *arrayofstructs, FieldTypes somevariable)
{
switch( somevariable )
{
case FIELD_X:
for (int i; i < 200; i++)
{
//Do stuff to arrayofstructs->test[i].x;
}
break;
case FIELD_Y:
for (int i; i < 200; i++)
{
//Do stuff to arrayofstructs->test[i].y;
}
break;
case FIELD_Z:
for (int i; i < 200; i++)
{
//Do stuff to arrayofstructs->test[i].z;
}
break;
}
}
如果意图始终执行相同的操作,但只是根据传递的值在结构的不同元素上执行,那么您可以这样做......
void somefunction(struct my_array_t *arrayofstructs, FieldTypes somevariable)
{
for (int i; i < 200; i++)
{
int* workingValue;
switch( somevariable )
{
case FIELD_X: workingValue = &arrayofstructs->test[i].x; break;
case FIELD_Y: workingValue = &arrayofstructs->test[i].y; break;
case FIELD_Z: workingValue = &arrayofstructs->test[i].z; break;
}
// do stuff to *workingValue -- no redundant code here
}
}