printf函数的异常输出 [英] Unexpected output of printf
问题描述
int类型的= 5;
浮动B = 3.5;
的printf(%D,B);
的printf(\\ n%F,一);
谁能告诉我为什么这个code是显示输出意外(垃圾\\ n3.5)
格式字符串不正确的错误,根据你的 A
和的声明b
:
的printf(%D,B); < - b为浮动错了!
的printf(\\ n%F,一); < - 一个是一个int错了! - 未定义行为
应该是:
的printf(%F,B);
的printf(\\ N%D,一);
问: - 为什么你得到的输出?
块引用>这是由于你的code的未定义行为:
国际标准©ISO / IEC ISO / IEC 9899:201X
7.16.1变量参数列表访问宏
(270页)
7.16.1.1的
的va_arg
宏
...]如果不存在实际下一个参数,或者如果类型不兼容
实际的下一个参数的类型(根据推广
默认参数促销),在的行为是理解过程网络定义
,除下列情况:结果
- 一类是符号整型
,另一种是
相应的无符号整数
键入和值重新presentable
在这两种类型;搜索
- 一类是指向无效
键,另一个是
指针为字符类型
块引用>int a=5; float b=3.5; printf("%d",b); printf("\n%f",a);
Can anyone please tell me why this code is showing unexpected output (garbage\n3.5)
解决方案Format string incorrect error, according to your declarations of
a
andb
:printf("%d",b); <-- "b is float" Wrong! printf("\n%f",a); <-- "a is an int" Wrong! -- Undefined behavior
should be:
printf("%f",b); printf("\n%d",a);
Q :- Why you getting that output?
It's due to undefined behavior of your code:
From INTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:201x
7.16.1 Variable argument list access macros
(page 270)
7.16.1.1 The
va_arg
macro[...] If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the
behavior is undefined
, except for the following cases:
— one type is asigned integer type
, the other type is the correspondingunsigned integer
type, and the value is representable in both types;
— one type is pointer tovoid
and the other is a pointer to a character type
这篇关于printf函数的异常输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!