printf 的意外输出 [英] Unexpected output of printf
问题描述
int a=5;浮动 b=3.5;printf("%d",b);printf("
%f",a);
谁能告诉我为什么这段代码显示意外输出(垃圾 3.5)
Format string wrong error,根据你对a
和b
的声明:
printf("%d",b);<-- "b 是浮动的" 错!printf("
%f",a);<-- "a is an int" 错误!-- 未定义的行为
应该是:
printf("%f",b);printf("
%d",a);
<块引用>
Q :- 为什么你得到那个输出?
这是由于您的代码的未定义行为:
来自 国际标准 ©ISO/IEC ISO/IEC9899:201x
<块引用>7.16.1 可变参数列表访问宏
(第 270 页)
7.16.1.1 va_arg
宏
[...] 如果没有实际的下一个参数,或者类型与实际下一个参数的类型(根据默认参数提升),行为未定义
,以下情况除外:
— 一种类型是有符号整数类型
,另一种类型是对应的无符号整数
类型,值是可表示的两种类型;
— 一种类型是指向 void
的指针,另一种是指向字符类型的指针
int a=5;
float b=3.5;
printf("%d",b);
printf("
%f",a);
Can anyone please tell me why this code is showing unexpected output (garbage 3.5)
Format string incorrect error, according to your declarations of a
and b
:
printf("%d",b); <-- "b is float" Wrong!
printf("
%f",a); <-- "a is an int" Wrong! -- Undefined behavior
should be:
printf("%f",b);
printf("
%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屋!