逆順ループのときに unsigned を避ける
from C言語逆引きメモ
逆順ループのときに unsigned を避ける
1ビットをケチるな
0→(-1)になろうとするときに値が一巡して終了条件を満たさなくなる
当たり前だけど普段スクリプト言語しか触ってないので抜けていた
code:overflow.c
#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main() {
for (uint64_t i = 5; i >= 0; --i) {
printf("%ld\n", i);
}
return 0;
}
なお、-Werrorコンパイラオプションを付けるとエラーにしてくれる
code:c
gcc -Wall -Wextra -pedantic -Werror -O0 overflow.c -o a.out && ./a.out | head -n 100
overflow.c: In function ‘main’:
overflow.c:6:28: error: comparison of unsigned expression in ‘>= 0’ is always true -Werror=type-limits
6 | for (uint64_t i = 5; i >= 0; --i) {
| ^~
cc1: all warnings being treated as errors