Reputation: 1229
I have a function which sets a variable based on another variable.
if(!button_x.on)
button_x.on = 1;
if(!button_y.on)
button_y.on = 1;
if(!button_z.on)
button_z.on = 1;
.
.
.
If it is x, y, z, …. is determined only at runtime. Having multiple such conditions for various(100s) different cases does not look good. Is there a better way to go about this in C?
EDIT: I should have better framed my example above.
if (!structureA.visited)
visit_structureA(); // does some operation
if (!structureB.visited)
visit_structureB();
if (!structureC.visited)
visit_structureC();
. . .
The number of structures and the name of the structure is not known at compile time. But the structure names follow a specific pattern shown above. It is known only at runtime. I tried using macros something like:
#define VISIT(str) \
if (!structure##str.visited) \
visit_structure##str();
//In the function:
// str = 'known at runtime'
VISIT(str);
But this would not work for obvious reason that preprocessor directives are replaced during compile time and not runtime. I am not sure if there is a better way for this?
Upvotes: 0
Views: 98
Reputation: 802
In C, the following condition:
if (!x)
x = 1;
is equivalent to:
x = 1;
if the variable is boolean (on/off), which I assume is the case if we are talking about buttons.
Upvotes: 1
Reputation: 137282
In your example, you set a variable value according to the same variable, not another one, if this is the case, and you want to change it from 0 to 1 and vice versa, you can do it without condition:
button_x.on = !button_x.on;
If you have many of those with the same idea of behavior, consider using array and itertating it.
Upvotes: 1