Tuesday, January 9, 2024

Is Objective-C BOOL a Boolean Type?

Juan Cruz Viotti:

While BOOL might look trivial, its definition is rather complex. It depends on which Apple platform and architecture you are targeting, which can result in unexpected behavior.


Recently, I stumbled into a case where for the same code, macOS Intel and macOS Apple Silicon invoked different overloads.


As we can see, the BOOL type is either an alias to bool or an alias to signed char depending on the value of the OBJC_BOOL_IS_BOOL preprocessor define.


More than a decade later, as part of the C99 specification, the C language released support for boolean values through the <stdbool.h> header. Then, later versions of the Objective-C runtime started conditionally aliasing BOOL to the new bool type in modern Apple products. It is likely that older platform and architecture combinations still use signed char for legacy reasons.

Update (2024-01-10): Greg Parker:

BOOL’s type and sign-edness affect Objective-C type encodings, which are used by NSArchives and Distributed Objects and others, which affects binary and data file compatibility. BOOL’s type also affects C and C++ function calls and data structures. It’s not easy to change.

See also: Hacker News.

1 Comment RSS · Twitter · Mastodon

I was never a fan of BOOL. The C "boolean" type (before happened) was `int` and 0 meant NO, and != 0 meant YES. Good enough. I have no idea, why anyone thought changing this was a **good** idea.

Apple defined BOOL as `char` and YES as 1. This produced serious problems. As soon as you define YES to be 1, you now have brittle code, that fails on x == YES, if x is for example 2. Fine in C, broken in ObjC. The idea with `char` was to conserve some space, for programmers, that were too lazy to use a bitfield, but cared about wasted space enough to not want to use an `int`. Using char though made dealing with method return values (think: IMP) that much more complicated :rolleyes:

Apple should have typedef-ed BOOL to int and only defined NO. Maybe they could have added a macro `#define is( x) (x != 0)` as a replacement for YES, so you can write: `if( is( [foo whatever])`, but why would you even want to...

Now its too late and you cant get rid of BOOL. The new C `bool` type is a weird un-C like type, thats basically just a char with a restrictive value set. I am not fan of it either.

Leave a Comment