printf 的意外输出 [英] Unexpected output of printf

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

问题描述

int a=5;浮动 b=3.5;printf("%d",b);printf("
%f",a);

谁能告诉我为什么这段代码显示意外输出(垃圾 3.5)

解决方案

Format string wrong error,根据你对ab的声明:

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 a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;
— one type is pointer to void and the other is a pointer to a character type

这篇关于printf 的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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