Why no non-short-circuit bitwise operators for booleans?

In the following real-world code example, continueTransaction() has side effects that must be observed.

// Calls continue transaction for each transaction once.
// Returns true if all transactions are done.
fn continueAllTransactionsOnce(self: *MainDevice) !bool {
    var all_done: bool = true;
    for (self.transactions.process_data) |*transaction| {
        all_done &= try self.port.continueTransaction(transaction);
    }
    return all_done;
}

Am I expected to cast this to u1 so I can use the bitwise operator to prevent short-circuiting?

Why are there no non-short-circuit boolean operators? Is there a better way to write this?

const done = try self.port.continueTransaction(transaction);
all_done = done and all_done;
1 Like

Booleans are for logic, short circuiting doesn’t violate boolean logic and is more efficient.

store the result of the side effecting operation in a separate variable.
Or move it to the front of the short circuit operation to give it priority

2 Likes

What does your function return? I tried mixing bool and & and could never avoid error: invalid operands to binary bitwise expression: 'bool' and 'bool'.

Am I expected to cast this to u1 so I can use the bitwise operator to prevent short-circuiting

You are expected to cast to some int type, though it doesn’t really have to do with short-circuiting or not. All the bitwise operations are only defined for integers. As @vulpesx points out, in Zig booleans are expressly only for Boolean logic. This can be a bit unexpected (pardon the pun) but the reasoning is pretty good imo. In Zig I never have to think about truthiness of a type, because only booleans, and optionals (a specialized boolean if you think about it) can be used in logical operations (if, while, etc).

all_done = 
    try self.port.continueTransaction(transaction) and all_done;

Can continueTransaction actually return false? Are you actually just trying to see if none of them error?

Yes! That is the only good way.

And errors :slight_smile:

2 Likes

Sure, If you write code that can fail. :smile:

Related: