warning: increment of a boolean expression
警告:真偽値(0/1)しか取れないbool型を加算した
[-Wbool-operation]
■1.bool型を++/--してはいけない
#include <stdbool.h>
#include <stdio.h>
//gcc/clang --トグル ++カウンターストップ
//VS2022 --カウンターストップ ++カウンターストップ
int main(void){
bool a = true;
bool b = false;
bool c = true;
bool d = false;
for(int i = 0; i < 10 ; i++){
printf("%d:%d:%d:%d\n",a--,b--,c++,d++);
}
}
0/1しか取れない bool 型変数を
++/--するのは多分誤りと思われます。
■2.gcc/clangの結果
1:0:1:0
0:1:1:1
1:0:1:1
0:1:1:1
1:0:1:1
0:1:1:1
1:0:1:1
0:1:1:1
1:0:1:1
0:1:1:1
先のプログラムをgccでコンパイルして動かすと上記になります。
ーー演算子がトグルになりますが、
これを利用しようとしてはいけません。
■3.vs2022の結果
1:0:1:0
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
0:0:1:1
先のプログラムをvs2022でコンパイルして動かすと上記になります。
gcc/clangと結果が異なります。
■4.トグルの実装(推奨)
#include <stdbool.h>
#include <stdio.h>
//トグルの実装bool型でなくても可能
int main(void){
bool a = true;
bool b = false;
for(int i = 0; i < 10 ; i++){
printf("%d:%d\n",a=1-a,b=1-b);
}
}
このように記述すると
コンパイラに依存せずにトグルを実装できます。
非推奨だった bool 型に対するインクリメント演算子を削除
https://cpprefjp.github.io/lang/cpp17/remove_deprecated_increment_of_bool.html