0

I was looking into Raspberry Pi Pico C/C++ SDK code. I found a statement using two inversion (not) operator next to each other.

What is the purpose of double inversion (not operator) in the statement return !!((*(io_ro_32 *)TBMAN_BASE) & TBMAN_PLATFORM_FPGA_BITS);?

Wouldn't the compiler strip these operation during optimization? What is the purpose of double inversion in a statement next to each other?

Code :

#if !PICO_NO_FPGA_CHECK
// Inline stub provided in header if this code is unused (so folding can be
// done in each TU instead of relying on LTO)
bool running_on_fpga() {
    return !!((*(io_ro_32 *)TBMAN_BASE) & TBMAN_PLATFORM_FPGA_BITS);
}
#endif
Dark Sorrow
  • 1,681
  • 14
  • 37
  • 1
    The datatype resulting from the `&` is not a boolean. One `!` will make it boolean, but the wrong 'polarity'... The second `!` gives the desired `true` or `false` to be returned. – Fe2O3 Aug 21 '22 at 03:03
  • 1
    @Fe2O3 Wouldn't C/C++ treat any non-zero value equivalent to boolean true? – Dark Sorrow Aug 21 '22 at 03:10
  • 2
    Yes, if the result of the `&` is 0, the function would return `false` without the filigree of ` ! ! ` otherwise it would return `true`. It's a big presumption to think that all code you see is written clearly and minimally. – Fe2O3 Aug 21 '22 at 03:12
  • 1
    The dup link of the dup link shows a possible context in which one would want exactly `1` as opposed to any non-zero `true`. In that, they summed two boolean values and check the result numerically, which wouldn't work with ambiguous true. Which I found rather neat, but no one seems to like it... – aulven Aug 21 '22 at 03:21
  • 1
    Note that C originally didn't have a `bool` (or `_Bool`) type. That apparently lead to some odd idioms that should no longer be needed. Especially not in C++. – BoP Aug 21 '22 at 07:34

0 Answers0