Alex Rivera | Logout

Why is a BOOL a signed char?

Asked 2010-09-30T23:42:26.520
10

The other day a user reported a bug to me about a toolbar item that was disabled when it should be been enabled. The validation code (simplified for your benefit) looked like:

- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem {

    NSArray* someArray = /* arrray from somewhere*/

    return [someArray count];
}

It took me a few minutes to realize that -count returns a 32-bit unsigned int, while BOOL is an 8-bit signed char. It just so happened that in this case someArray had 768 elements in it, which meant the lower 8-bits were all 0. When the int is cast to a BOOL upon returning, it resolves to NO, even though a human would expect the answer to be YES.

I've since changed my code to return [someArray count] > 0; however, now I'm curious why is BOOL really a signed char. Is that really "better" in some way then it being an int?

Edit
Report

1 Answer

3

An obvious answer is that it's four times smaller (on typical 32-bit and 64-bit architectures), and also doesn't have any alignment requirements.

answered 2010-09-30T23:46:36.587

Your Answer