Objective-Cでの真偽値型

  • BOOL
  • bool
  • Boolean

Objective-C内で使える真偽値型として次の3つがあるのだけど、どれを使うのが正しいのかよくわからない。

実は型だけではなく値の方もいくつかある。

  • true
  • TRUE
  • YES

こうなると、boolにYESを入れればいいのか、BOOLにtrueを入れればいいのかもうなんだかよくわかんなくなっちゃったので簡単にまとめてみた。

BOOL

Objective-C 標準の真偽値型(なのかな)

    • YES
    • 値は1
    • NO
    • 値は0
/* objc.h */
...
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
...

bool

ISO C/C++ 標準の真偽値型。

    • true
    • 値は1
    • false
    • 値は0
/* stdbool.h */
...
/*
 * ISO C Standard:  7.16  Boolean type and values  <stdbool.h>
 */

#ifndef _STDBOOL_H
#define _STDBOOL_H

#ifndef __cplusplus

#define bool	_Bool
#define true	1
#define false	0

#else /* __cplusplus */

/* Supporting <stdbool.h> in C++ is a GCC extension.  */
#define _Bool	bool
#define bool	bool
#define false	false
#define true	true

#endif /* __cplusplus */
...

Boolean

Mac OS historical type」とのこと。

    • true
    • 値は1
    • false
    • 値は0
/* MacTypes.h */
...
/********************************************************************************

    Boolean types and values
    
        Boolean         Mac OS historic type, sizeof(Boolean)==1
        bool            Defined in stdbool.h, ISO C/C++ standard type
        false           Now defined in stdbool.h
        true            Now defined in stdbool.h
        
*********************************************************************************/
typedef unsigned char                   Boolean;
...

まとめ

結局はどの型やどの値を使っても問題なく動きそうだということがわかったのだけど、せっかくObjective-Cで書いているんだからおれはBOOL型(とYESとNO)を使うぜ、という結論に至ったよ。