2
0

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 1 year has passed since last update.

[C++] true の数を数える小技

Posted at

bool値を+で足し合わせると、true の個数を出せる。

const auto num = true + true + false ; // 2

無論、変数でも使える。

void func(
  const bool val_0,
  const bool val_1,
  const bool val_2
)
{
  const auto num = val_0 + val_1 + val_2 ;
}

解説

足し算を行う際に、bool は int へキャストされる。
この際、false は 0 に、true は 1 に、変換される。

true + true + false => 1 + 1 + 0

結果として、true の数が出てくる。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?