c语言诡异程序,C语言里整型比较的一个诡异之处

以下代码定义了一个整型int_min,值为0x80000000。在计算机补码表示法下,0x80000000是int可表示的最小的数。

然后取int_min的负数,根据补码运算规则,-int_min的位模式和int_min相同,也等于0x80000000。

神奇的事情来了,-int_min = int_min < 0 竟然不成立。

#include

#include

void test_int_min() {

int int_min = 0x80000000;

assert(int_min == INT_MIN); // True

assert(int_min < 0); // True

assert(int_min == -int_min); // True

assert(-int_min < 0); // False

}

在so上面找到了一个类似问题 Why is 0 < -0x80000000?,猜测-int_min和0比较的时候自动转换成了unsigned类型,于是对-int_min进行强制类型转换,没想到依然是False。

assert((int)-int_min < 0); // False

再考虑到可能是编译器的问题,但是不论windows+mingw64+gcc8.1还是Kali+gcc8.2编译运行结果都是一样,用gbd单步调试得到的结果也是-int_min < 0。

bVbrQGY?w=501&h=237

编译是用的最简单的命令gcc test_int_min.c -o test_int_min,没有额外编译参数。

补充1:完成操作流程。

PS E:\Repository\csapp\tests> Get-WmiObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption

Microsoft Windows 10 教育版

PS E:\Repository\csapp\tests> gcc --version

gcc.exe (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 8.1.0

Copyright (C) 2018 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.

PS E:\Repository\csapp\tests> cat t.c

#include

#include

void test_int_min() {

int int_min = 0x80000000;

assert(int_min == INT_MIN); // True

assert(int_min < 0); // True

assert(int_min == -int_min); // True

assert(-int_min < 0); // False

}

int main(int argc, char const *argv[])

{

test_int_min();

return 0;

}

PS E:\Repository\csapp\tests> gcc t.c -o t.exe

PS E:\Repository\csapp\tests> .\t.exe

Assertion failed!

Program: E:\Repository\csapp\tests\t.exe

File: t.c, Line 9

Expression: -int_min < 0

PS E:\Repository\csapp\tests> bash

kali@A003657-PC01:/mnt/e/Repository/csapp/tests$ cat /etc/issue

Kali GNU/Linux Rolling \n \l

kali@A003657-PC01:/mnt/e/Repository/csapp/tests$ gcc --version

gcc (Debian 8.2.0-13) 8.2.0

Copyright (C) 2018 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.

kali@A003657-PC01:/mnt/e/Repository/csapp/tests$ gcc t.c -o t

kali@A003657-PC01:/mnt/e/Repository/csapp/tests$ ./t

t: t.c:9: test_int_min: Assertion `-int_min < 0' failed.

Aborted (core dumped)

kali@A003657-PC01:/mnt/e/Repository/csapp/tests$

补充2:在centos7+gcc4.8环境下能得到预期结果。

bVbrQHS?w=749&h=182

有人能解释一下吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值