关于C数据类型和常量的问题 [英] Question about C datatype and constant

查看:117
本文介绍了关于C数据类型和常量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候!
我正在尝试用C语言,直到遇到一些非常奇怪的东西。
我无法向自己解释下面显示的结果。

Greetings! I was experimenting with C language till I encountered something very strange. I was not able to explain myself the result shown below.

代码:

#include <stdio.h>

int main(void)
{
    int num = 4294967295U;
    printf("%u\n", num);
    return 0;
}

问题:

1。)如你所见,我创建了一个 int ,它可以保存 -2147483648 2147483647 。

1.) As you see, I created an int which can hold numbers between -2147483648 to 2147483647.

2。)当我将值 4294967295 分配给此变量时,IDE会在此期间向我显示警告消息编译,因为变量溢出。

2.) When I assign the value 4294967295 to this variable, the IDE shows me a warning message during compilation because the variable overflowed.

3。)由于好奇,我在数字后面添加了一个 U(无符号),当我重新编译它时,编译器没有返回任何警告信息。

3.) Due to curiosity I added a U (unsigned) behind the number and when I recompiled it, the compiler did not return any warning message.

4。)我通过将 U(无符号)更改为 L进行了进一步的实验(长) LL(很长)。正如预期的那样,警告消息仍然存在于这两个中,但在我将其更改为 UL(无符号长) ULL(无符号长长)之后仍然存在。

4.) I did further experiments by changing the U (unsigned) to L (long) and LL (long long). As expected, the warning message still persist for these two but not after I change it to UL (unsigned Long) and ULL (unsigned long long).

5。)为什么会发生这种情况?

5.) Why is this happening?

警告信息:(对于步骤2)

warning #2073: Overflow in converting constant expression from 'long long int' to 'int'.

警告信息:(对于步骤4 LL & L

The Warning Message:(For steps 4 LL & L)

warning #2073: Overflow in converting constant expression from 'long long int' to 'long int'.

最后,感谢您阅读我的问题,非常感谢您的教导和建议。

推荐答案

也许,默认情况下,编译器假定您输入的是有符号整数。当你给它 4294967295 时,这个数字不适合4字节整数,所以它使用一个8字节的整数来存储它。然后它必须进行有损转换( long long ,AKA 8-byte, long ,AKA 4-byte ),所以它会给你一个警告。

Perhaps, by default, the compiler assumes you're typing in signed integers. When you give it 4294967295, that number doesn't fit into a 4-byte integer, so it uses an 8-byte integer to store it, instead. Then it has to do a lossy conversion (long long, AKA 8-byte, to long, AKA 4-byte), so it gives you a warning.

但是,当你输入 4294967295U 时,它知道你想要一个无符号的整数。该数字适合4字节无符号整数,因此它的类型为 long int ,并且不需要有损转换。 (你不会通过从 unsigned long int long int 来丢失数据,只是错误地表示它。)

However, when you type 4294967295U, it knows you want an unsigned integer. That number fits into a 4-byte unsigned integer, so it has type long int, and no lossy conversion is necessary. (You're not losing data by going from unsigned long int to long int, just mis-representing it.)

这篇关于关于C数据类型和常量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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