Use -Wshift-count-negative
flag to warn bit shifting of a negative amount.
#include <stdio.h>
int main()
{
int x = 8;
int y = x << -1;
printf("%d\n", y);
return 0;
}
The result of arithmetics is undefined if we perform bit shifting by a negative amount, which may lead to unexpected behavior.
$ # M1 Mac (Monterey) + Apple clang 13.1.6
$ clang sample.cpp -o sample -Wshift-count-negative
sample.cpp:6:15: warning: shift count is negative [-Wshift-count-negative]
int y = x << -1;
^ ~~
1 warning generated.
$ ./sample
8
The warnings are displayed automatically: clang enables -Wshift-count-negative
by default.
$ # M1 Mac (Monterey) + Apple clang 13.1.6
$ clang sample.cpp
sample.cpp:6:15: warning: shift count is negative [-Wshift-count-negative]
int y = x << -1;
^ ~~
1 warning generated.
Suppress warnings
Use -Wno-shift-count-negative
to suppress warnings.
$ # M1 Mac (Monterey) + Apple clang 13.1.6
$ clang sample.cpp -Wno-shift-count-negative
$
References
- Clang documentation — DIAGNOSTIC FLAGS IN CLANG
https://clang.llvm.org/docs/DiagnosticsReference.html#wshift-count-negative