具有Long Int的%d [英] %d with Long Int

查看:52
本文介绍了具有Long Int的%d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码正确吗?据我所知,它应该不能正常工作,但是在Dev-C ++编译器上,它可以.请有人详细解释吗?

Is the following code Correct?As far as my understanding,it should not work properly,but on the Dev-C++ Compiler,it does.Could someone explain in detail please?

#include<limits.h>

int main()
{
long int num_case=LONG_MAX;

scanf("%d",&num_case);

printf("%ld",num_case);
return 0;
}

谢谢

推荐答案

就像标准C库告诉您不要执行的大多数操作一样,它会调用未定义的行为.未定义意味着它可能会在某些条件下工作,但在您最不希望的情况下崩溃.

Like most things that the standard C library tells you not to do, it invokes undefined behavior. Undefined means it might work under some conditions yet crash when you least expect it.

在这种情况下,它是有效的,因为 long int int 实际上是相同的数字表示形式:四字节,二进制补码.在另一个平台(例如x86-64 Linux)上,情况可能并非如此,您可能会看到某种问题.特别是,8字节 long int 的高位字节将不被初始化.

In this case, it works because long int and int are actually the same numeric representation: four byte, two's complement. With another platform (for example x86-64 Linux), that might not be the case, and you would probably see some sort of problem. In particular, the high-order bytes of the 8-byte long int would be left uninitialized.

编辑:问但它会崩溃"是错误的思路.根据语言标准,仅将未初始化的字节读取到 long int 类型的变量中就可以使C程序崩溃.我们不需要查找这样做的平台示例即可了解该程序的指定不正确.这就是我想说的.C不会立即将规则手册扔给您,它会等到您移植并破坏最初的假设为止.

Asking "but will it crash" is thinking the wrong way. Merely reading uninitialized bytes into a variable of type long int is allowed to crash a C program, according to the language standard. We don't need to find an example of a platform which does so, to understand that the program is ill-specified. That is the point. C does not throw the rulebook at you right away, it waits until you port and break initial assumptions.

这篇关于具有Long Int的%d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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