【问题标题】:How can I track a value of a boolean at runtime?如何在运行时跟踪布尔值?
【发布时间】: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 中没有这种魔力。您需要编写一个查看输入的函数。
  • 对,只要定义一个函数。由于它很短,编译器可能会内联它,所以开销应该很小。

标签: c struct boolean


【解决方案1】:

你需要使用一个函数:

bool is_any_on(light_t *light)
{
    return light->led.is_on || light->candle.is_on;
}

然后这样称呼它:

is_any_on(&light1)

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多