看汇编
g++ -S test.cpp
我这边测试,不同的优化选项,结果不同。有优化时,代码中直接就是编译器计算出来的常数结果。
signed integer overflow是undefined behavior
https://www.gnu.org/software/autoconf/manual/autoconf-2.64/html_node/Signed-Overflow-Examples.html
用unsigned来处理是一个办法。之前貌似本站还有一个帖子是主张要完全取消unsigned的。
happy@TheTAO-00:~$ g++ 1.cpp
happy@TheTAO-00:~$ ./a.out
0
1
happy@TheTAO-00:~$ g++ -O3 1.cpp
happy@TheTAO-00:~$ ./a.out
0
0
happy@TheTAO-00:~$ g++ -O1 1.cpp
happy@TheTAO-00:~$ ./a.out
0
1
happy@TheTAO-00:~$ g++ -O2 1.cpp
happy@TheTAO-00:~$ ./a.out
0
0
xxx@The-00:~$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
g++ 1.cpp的结果(不带-O参数):
main:
.LFB1493:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $2147483647, -4(%rbp)
movl -4(%rbp), %eax
addl $1, %eax
addl %eax, %eax
movl %eax, %esi
leaq _ZSt4cout(%rip), %rdi
call _ZNSolsEi@PLT
movq %rax, %rdx
movq _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax
movq %rax, %rsi
movq %rdx, %rdi
call _ZNSolsEPFRSoS_E@PLT
movl -4(%rbp), %eax
addl $1, %eax
addl %eax, %eax
testl %eax, %eax
sete %al
movzbl %al, %eax
movl %eax, %esi
leaq _ZSt4cout(%rip), %rdi
call _ZNSolsEb@PLT
movq %rax, %rdx
movq _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax
movq %rax, %rsi
movq %rdx, %rdi
call _ZNSolsEPFRSoS_E@PLT
movl $0, %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
g++ -O2 1.cpp的结果:
main:
.LFB1564:
.cfi_startproc
leaq _ZSt4cout(%rip), %rdi
subq $8, %rsp
.cfi_def_cfa_offset 16
xorl %esi, %esi
call _ZNSolsEi@PLT
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@PLT
leaq _ZSt4cout(%rip), %rdi
xorl %esi, %esi
call _ZNSo9_M_insertIbEERSoT_@PLT
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@PLT
xorl %eax, %eax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
g++ -O1 -S 1.cpp
main:
.LFB1564:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $0, %esi
leaq _ZSt4cout(%rip), %rdi
call _ZNSolsEi@PLT
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@PLT
movl $1, %esi
leaq _ZSt4cout(%rip), %rdi
call _ZNSo9_M_insertIbEERSoT_@PLT
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@PLT
movl $0, %eax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
--
修改:z16166 FROM 125.35.120.*
FROM 125.35.120.*