开发者

Is printf("%d", 1.0) undefined?

According to section 4.9.6.1 of the C89 draft, %d is a character that 开发者_如何转开发specifies the type of conversion to be applied.

The word conversion implies, in my opinion, that printf("%d", 1.0) is defined.

Please confirm or refute this.


The conversion is the conversion of a language value to a lexical representation of that value.

Your theory is wrong; behavior is undefined. The spec says (7.19.6.1p8 and 9, using C99 TC2):

The int argument is converted to signed decimal in the style [−]dddd.

And

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


Printf is a varargs function, so no conversion is possible. The compiler just arranges to push a double onto the arguments list. Printf has no way to find out that it's a double versus an int versus an elephant. Result? Chaos.


The word "conversion" here is referring to the conversion of an int (which is the only acceptable argument type here) to a string of characters that make of the decimal representation of that int. It has nothing to do with conversion from other types (such as double) to int.


Not sure if it's officially undefined or an error - but it's wrong!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜