Last Update 2021/09/14
-Wshift-count-negative
シフト演算の祭に、シフトカウントが負の値の場合に警告を出力
テスト概要
オプション無し、-Wshift-count-negativeオプションを使用した際の警告出力例
実行環境
GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1
GNU C Library 2.28
GNU Binutils 2.31.1
コード例・出力内容中の表記
・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
使用ファイル
sample.c
#include <stdio.h>
int main(void)
{
/* シフトカウントが正の値 */
printf("%d\n", 8 >> 2);
printf("%d\n", 8 << 2);
/* シフトカウントが負の値 */
printf("%d\n", 8 >> -2);
printf("%d\n", 8 << -2);
return 0;
}
動作テスト
オプション無しでコンパイルを実行
$ gcc sample.c
sample.c: In function ‘main’:
sample.c:10:19: warning: right shift count is negative [-Wshift-count-negative]
printf("%d\n", 8 >> -2);
^~
sample.c:11:19: warning: left shift count is negative [-Wshift-count-negative]
printf("%d\n", 8 << -2);
^~
$ ./a.out 左右シフトカウントが負の値である事に関して警告を出力
2
32
32
2
$ 負の値の場合は逆向きシフトで演算
-Wshift-count-negativeオプション使用してコンパイルを実行
$ gcc -Wshift-count-negative sample.c
sample.c: In function ‘main’:
sample.c:10:19: warning: right shift count is negative [-Wshift-count-negative]
printf("%d\n", 8 >> -2);
^~
sample.c:11:19: warning: left shift count is negative [-Wshift-count-negative]
printf("%d\n", 8 << -2);
^~
$ -Wshift-count-negativeオプションはデフォルトで有効であるためオプション無しと同じ結果となる