c++ - 在这种情况下 sizeof(int) 返回什么?

标签 c++ c sizeof turbo-c++

#include<stdio.h>
#include<conio.h>

void main()
{   
    if(sizeof(int)>=-2)    
        printf("True");
    else
        printf("False");
}

当我尝试使用 Turbo C++ 编译这段代码时,它返回 False 而不是 True 。 但是当我尝试打印 int 的值时,程序返回 2。

这怎么可能?而 sizeof(int) 返回 2 并且是 2>=-2 。

最佳答案

sizeof(int)std::size_t 类型替换,在大多数实现中 都是无符号的。

比较有符号和无符号会导致奇怪的结果,因为有符号被提升为无符号。

你可以得到如下所示的合理结果

if(static_cast<int>(sizeof(int)) >= -2)

如果您正在使用 C 编译器

if((int)sizeof(int) >= -2)

例如,使用一些警告标志 -Wall 编译您的代码应该最有可能警告有符号/无符号比较。 (如果您没有忽略警告)

关于c++ - 在这种情况下 sizeof(int) 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26609042/

相关文章:

C++ 概念 : How to use 'concept' to check the property of a templated struct?

c++ - 为什么没有 cdirent 或 sys/cstat

c - msgsnd 无权限错误

C: 自定义 strlen() 库函数

c++ - 在 C++ 中将字符串转换为 int 获得更小的值 Visual Studio 2013

c++ - std::string 和 placement new

c - 注入(inject)数据包以终止 TCP 连接

c - 将文件中的数字读入数组

c - 在不编译和执行代码的情况下找到类型大小的最简单方法是什么?

c - 像 snprintf 这样的函数中的 size_t 混淆