为什么的printf("%F",0);给未定义行为? [英] Why does printf("%f",0); give undefined behavior?

查看:271
本文介绍了为什么的printf("%F",0);给未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语句的printf(%F \\ N,0.0); 0打印结果
不过,声明的printf(%F \\ N,0); 打印随机值。

The statement printf("%f\n",0.0f); prints 0.
However, the statement printf("%f\n",0); prints random values.

我知道我表现出某种不确定的行为,但我想不出为什么特别。

I realize I'm exhibiting some kind of undefined behaviour, but I can't figure out why specifically.

一个浮点值,其中所有的位为0仍是一个有效的浮动与0结果值
浮动 INT 是我的机器上相同大小(如果,甚至是相关的)。

A floating point value in which all the bits are 0 is still a valid float with value of 0.
float and int are the same size on my machine (if that is even relevant).

为什么使用文本,而不是原因此行为浮动文字在的printf 点整数?

Why does using an integer literal instead of a floating point literal in printf cause this behavior?

推荐答案

%F格式需要键入双参数。你让这类型的 INT 参数。这就是为什么行为是不确定的。

The "%f" format requires an argument of type double. You're giving it an argument of type int. That's why the behavior is undefined.

该标准不保证所有位归零是 0.0 (虽然它经常是),或任何<$ C的有效再presentation $ C>双击价值,或者说 INT 双击大小相同(请记住这是双击,而不是浮动),或者,即使他们是相同的大小,他们正在作为参数传递以相同的方式可变参数函数。

The standard does not guarantee that all-bits-zero is a valid representation of 0.0 (though it often is), or of any double value, or that int and double are the same size (remember it's double, not float), or, even if they are the same size, that they're passed as arguments to a variadic function in the same way.

这可能发生在你的系统上的工作。这是未定义行为最坏的症状,因为它使人们难以诊断错误。

It might happen to "work" on your system. That's the worst possible symptom of undefined behavior, because it makes it difficult to diagnose the error.

N1570 7.21.6.1第9段:

N1570 7.21.6.1 paragraph 9:

...如果任何参数都不是正确的类型对应的
  转换规范,行为是不确定的。

... If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

类型的参数浮动都提升到双击,这就是为什么的printf( %F \\ N,0.0)的作品。整数类型比 INT 窄的参数都提升到 INT unsigned int类型。这些促销规则(由N1570 6.5.2.2款规定的6)不要在中的printf(%F \\ N,0)

Arguments of type float are promoted to double, which is why printf("%f\n",0.0f) works. Arguments of integer types narrower than int are promoted to int or to unsigned int. These promotion rules (specified by N1570 6.5.2.2 paragraph 6) do not help in the case of printf("%f\n", 0).

这篇关于为什么的printf(&QUOT;%F&QUOT;,0);给未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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