为什么sizeof类型与整数比较返回false [英] why sizeof type compared with integer returns false

查看:56
本文介绍了为什么sizeof类型与整数比较返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中发现了一种奇怪的行为.

one strange behaviour I noticed in below code.

#include<stdio.h>
#include <stdbool.h>

int main()
{
int x = sizeof(int) > -1;

bool z = sizeof(int);

printf("x is %d \t z is %d \n",x,z);
if(sizeof(int)>-1)
{
printf("true\n");
}
else
printf("false\n");
}

sizeof(int)> -1 为true且预期输出应为1时,为什么int x为零.

Why int x is zero when sizeof(int) > -1 is true and the expected output should be 1.

推荐答案

sizeof 运算符产生的不是 int ,而是产生的 size_t 无符号整数类型.当您将有符号整数(如-1)与无符号整数进行比较时,最终将比较错误的值.

The sizeof operator yields not an int but size_t which is an unsigned integer type. When you compare a signed integer like -1 to an unsigned integer you will end up comparing the wrong values.

进行以下更改,代码将按预期工作.

Do the following changes and the code will work as expected.

#include<stdio.h>

#include <stdbool.h>

int main()
{
    int x = (int)sizeof(int) > -1;

    bool z = sizeof(int);

    printf("x is %d \t z is %d \n",x,z);
    if((int)sizeof(int) > -1)
    {
        printf("true\n");
    }
    else
        printf("false\n");
}

输出:

x is 1   z is 1
true

这篇关于为什么sizeof类型与整数比较返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆