【发布时间】:2020-08-06 18:09:44
【问题描述】:
我想定义一个布尔值来跟踪其他两个布尔值的值并在它们发生变化时动态更新,我该如何实现?
#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"?
我可以通过一个函数来实现这一点,但我可以不这样做吗? 我想使用布尔指针也无济于事,因为我对两个布尔值的结果感兴趣。
【问题讨论】:
-
C 中没有这种魔力。您需要编写一个查看输入的函数。
-
对,只要定义一个函数。由于它很短,编译器可能会内联它,所以开销应该很小。