Bool vs BOOL

Possible duplicates:
Objective-C: BOOL vs bool
Is there a difference between BOOL and Boolean in Objective-C?

I noticed from autocompletion in Xcode that there are bool and BOOL in Objective-C. Is it different? Why are there two different types of bool?

Are they interchangeable?

+5
source share
4 answers

Yes, they are different.

  • C ++ has bool, and it is a true boolean type. It is guaranteed to be 0 or 1 in an integer context.
  • C99 _Bool , <stdbool.h> , bool _Bool ( true false 1 0 ).
  • Cocoa bool , typedef signed char. , 0 1.
  • Carbon Boolean , typedef unsigned char. , Cocoa bool , 0 1.

Cocoa "" false, true.

+9

BOOL Objective-C typedef signed char BOOL, BOOL - , C99.

+3
+2

bool, , bool, bool , bool - . " "? , , :

#define FLAG_A 0x00000001
#define FLAG_B 0x00000002
...
#define FLAG_F 0x00000020
struct S
{
    // ...
    unsigned int flags;
};

void doSomething(S* sList, bool withF)
{
    for (S* s = sList; s; s = s->next)
    {
        if ((bool)(s->flags & FLAG_F) != withF)
            continue;
        // actually do something
    }
}

since it (bool)(s->flags & FLAG_F)can be used to evaluate either 0 or 1. If it was boolinstead boolof throwing, it would not work, because it withFevaluates to 0 or 1, but (bool)(s->flags & FLAG_F)0 or the numeric value FLAG_F, which in this case is not equal to 1.

This example is far-fetched, yes, but real errors of this type can and do happen too often in old code that does not use the true Boolean types C99 / C ++.

+2
source

All Articles