我想定义一个布尔值,它可以跟踪另外两个布尔值的值,并在它们变化时动态更新,如何实现?
#include <stdio.h>
typedef struct candle_s {
bool is_on;
int flame_size;
}candle_t;
typedef struct led_s {
bool is_on;
int ampers;
}led_t;
typedef struct light_s {
bool is_any_on;
candle_t candle;
led_t led;
}light_t;
int main()
{
light_t light1;
light1.led = {0, 10};
light1.candle = {1, 20};
light1.is_any_on = light1.led.is_on | light1.candle.is_on;
printf("Is any on: %d, is light on %d, is candle on %d\n",
light1.is_any_on, light1.led.is_on, light1.candle.is_on);
light1.candle.is_on = 0;
printf("Is any on: %d, is light on %d, is candle on %d\n",
light1.is_any_on, light1.led.is_on, light1.candle.is_on);
return 0;
}
程序输出。
Is any on: 1, is light on 0, is candle on 1
Is any on: 1, is light on 0, is candle on 0
如何让is_any_on变成 “0”?
我可以用一个函数来实现,但我可以用其他方法来实现吗?我想使用布尔指针也不会有什么帮助,因为我对两个布尔值的结果感兴趣。
解决方案:
你需要使用一个函数。
bool is_any_on(light_t *light)
{
return light->led.is_on || light->candle.is_on;
}
然后像这样调用它:
is_any_on(&light1)