|= and ? operations

I have a line of code here and I am trying to determine how the variable value is being calculated:

 
   value |= gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24)) ? 0 : 1;


I understand that a |= b; is just syntactic sugar for a = a | b; but what is happening with the mod operation at the end of the line? I am not sure what ? 0 : 1 is doing.
closed account (E0p9LyTq)
? is the conditional ternary operator. condition ? result1 : result2

AKA the conditional operator.

https://en.cppreference.com/w/cpp/language/operator_other

It's a fancy way of doing if/else.

So value is being set to 0 or 1 by the 0 : 1 and not by the state of the gpio pin? In other words, it seems to be detecting if the pin exists and if it does it sets the value to a 1 and if it does not then it sets the value to 0, does that sound right?

closed account (E0p9LyTq)
gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24)) is the condition being evaluated.

1
2
3
4
5
6
7
8
if (gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24)))
{
    // result is 0
}
else
{
    // result is 1
}


The result is then being bitwise ORed with value.
@FurryGuy Okay I just wanted to make sure, thanks!
which is also the same as this, I believe, you can check it:

value |= (gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24) == 0);
It could also be written as
value |= !gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24));
closed account (E0p9LyTq)
value |= !gpio_get_value(IOMUX_TO_GPIO(MX51_PIN_EIM_A24));

Doesn't that assume the function returns either 0 or 1? Given what the ternary operator's results are.

What if it returned a "true" value that is greater than 1? Wouldn't that muck up the bit ORing?


Brain fart over now.
Last edited on
once you put anything inside a Boolean expression it will result in 1 or 0.
The ! will convert 0 to 1 and any non-zero to 0.
Last edited on
Topic archived. No new replies allowed.