9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C99 の bool と int の振る舞い

Last updated at Posted at 2013-03-18

C99 でようやく bool型 ( _Bool 型 ) が導入された。
わざわざ導入されたからにはやはり int とは振る舞いが異なる。

c99bool.c
//  compiled with "-std=c99"

# include <stdio.h>
# include <stdbool.h>

int main()
{
    bool boolval=2; // _Bool型 に 0 以外の値を入れると 1 になる。
    printf( "%d\n", boolval ); //=> 1
    ++boolval; // ++ はエラーにならないが、1のまま。
    printf( "%d\n", boolval ); //=> 1
    --boolval; // 1 に対して -- すると、0 になる。
    printf( "%d\n", boolval ); //=> 0
    --boolval; // 0 に対して -- しでも -1 にはなれないので、1 になる。
    printf( "%d\n", boolval ); //=> 1
    boolval ^= 5; // ビットの順序とは関係なく「0以外を代入すると1になる」ので、1になる。
    printf( "%d\n", boolval ); //=> 1
    boolval<<=1; // シフトでも「0以外を代入すると1になる」というルールにより、1になる。
    printf( "%d\n", boolval ); //=> 1
    boolval = 0.01; // (int)0.01 は 0 だが、bool に入れると 1 になる。
    printf( "%d\n", boolval ); //=> 1

    return 0;
}

_Bool 型の変数は、値が 0 か 1 のいずれかにしかならない。
BOOL 型の引数が 0, 1 以外の値を取りうることを利用したコードを見てぐったりしたことがあるが、_Bool ならそういう心配がない。

桁あふれした場合の動作が他の整数型と違うので、そこに注目すると気持ち悪い感じもするが、よく考えるとまあこうする他ない。と思う。

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?