0xFF from intFromBool impossible?

Once again I had 2 bools with non-binary values today. Others working fine.

So I have this at top level of main zig file:

var impossibleCodeEntered: bool = false;

Later on some code is triggered as though the value is true.

When I do an intFromBool, it returns 0xFF (pretty sure my bare-metal uart logging is telling the truth here).

const madness: u8 = @intFromBool(impossibleCodeEntered);
gasm.logU8(madness);

However this still evaluates true:

if (madness == 1)

All of this works as expected if I add an assignment at the top of main().

impossibleCodeEntered = false;

Is it possibly 0xFF is some kind of internal marker for uninitialized memory that I should not be seeing? I am developing a bare-metal OS in Zig, so there is a chance the problem is between the chair and keyboard :slight_smile: but it just seems such a basic thing to go wrong, that I have no idea what to think.

This isnt the first time I’m seeing strange aarch64 memory values: (ignore the FP stuff, that is fixed)

I am guessing that @sizeOf(bool) is 4 (32bit) and a ā€œbinary notā€ instruction is used to toggle the boolean value (i.e. zeros become ones for all 32bit and vice versa).
Examining the generated assembly code can confirm my hypothesis.

1 Like

From the machine code perspective, a true/false decision is a test for zero. So true can be any non zero value.

Depending on optimization level the compiler might even invert the logic so you have an ā€˜is_valid’ Boolean in a register and the optimizer might decide to keep a not_is_valid value, as long as the code behaves the same.

The expression result might even live only in a single bit flag register on some architectures.

The if statement in C is defined accordingly, taking the false branch for zero and the true branch for every other value.

If you just cast such a value, only 0 for false is guaranteed, otherwise the compiler would need to add a load for a true literal.

So even if true is defined as 1 that’s not what’s necessarily used by the machine code to signify a truth value.

If you want that use an if(bool) 1 else 0;

1 Like

>Examining the generated assembly
Thanks. My arm cheat-sheet says MVN, but objdump -d hasnt revealed any, and my attempts to add some extra instructions to help seem to be optimized away.

Thanks. The problem here is that the bool var starts life as false, but is later being evaluated as true, unless I set to false again at the top of main. ie I am not setting it to true. It just seems to be defaulted to a non zero value.

But what you say makes a lot of sense, however I would still expect intFromBool to honor it’s contract in a binary way ie. returning 1 or 0.