views:

90

answers:

3

I'm writing an iPhone app that's a mixture of Objective-C and C. I have 32-bit integer flags throughout my code that take on only two distinct values: 0 and 1. I'd like to use a data type that's smaller than 32 bits.

Is there a type that's only one bit? What is the size of "BOOL" in Objective-C?

One solution I've considered is using one 32-bit integer for a group of 32 flags... then checking each flag in the following way:

if(ALL_FLAGS & (1 << SPECIFIC_FLAG)){...}

I'd really like to use just a "bit" type though.

Cheers!

+4  A: 

The BOOL type under Objective C (actually it's a Cocoa definition, OBJC itself doesn't know the BOOL type) is using one byte. This is different from the Windows 32 BOOL which is equivalent to int or 32 bit.

With smaller types you can use the typical C/C++ methods, either with bit shifts like in your example above or bit structures (in which case the compiler will do the bit shifting and testing).

typedef struct {
    unsigned someflag:1;
    unsigned anotherflag:1;
    unsigned yetnoather:1;
} MYFLAGS ;


MYFLAGS allflags;  

allflags.anotherflag= TRUE; 

if (allflags.anotherflag) { /* somecode */ }
Nicholaz
+1, but where does the definition of `TRUE` come from? Standard C uses `0` and `1` (actually, anything `!= 0` is considered true) or `true` and `false` if you include `stdbool.h`; afaik Objective C uses `YES` and `NO`; and just for further confusion: the C99 boolean type is called `_Bool`
Christoph
in CFBase.h: `#define TRUE 1`
cobbal
Wouldn't this construct still be padded by the compiler to something larger than 3 bits though, making the whole exercise a bit questionable.
Fred
@fred: Yes, it will be rounded up (I guess the final size will depend on compiler and struct padding settings). The whole thing of course pretty much depends on what the author of the question wants to do ... I mean personally, for three flags, I'd just go with a single byte BOOL.
Nicholaz
+3  A: 

There is also a CFBitVector, in which you could hold sets of values...

Kendall Helmstetter Gelner
+1  A: 

Here are the definitions for the BOOL type, you could define your own type in the same way:

typedef signed char  BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED


#define YES             (BOOL)1
#define NO              (BOOL)0
jessecurry