当我使用了错误的格式说明会发生什么? [英] What happens when I use the wrong format specifier?

查看:126
本文介绍了当我使用了错误的格式说明会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道,当我使用了错误的格式说明用C会发生什么?

例如:

  X ='A';
的printf(%C \\ n,x)的;
的printf(%d个\\ N,X);X = 65;
的printf(%C \\ n,x)的;
的printf(%d个\\ N,X);X = 128;
的printf(%d个\\ N,X);


解决方案

  

当我使用C中的错误格式说明会发生什么情况?


一般来说,不确定的行为。 *

不过,记得的printf 是一个可变参数函数,并且参数参数可变型函数经历的默认参数提升的。因此,例如,一个字符被提升到一个 INT 。因此,在实践中,这些都将得到同样的结果:

 字符X ='A';
的printf(%C \\ n,x)的;INT Y ='A';
的printf(%C \\ N,Y);

而这是不确定的行为:

 长Z ='A';
的printf(%C \\ N,Z);



<子> *见例如部分C99标准的7.19.6.1 P9:


  

如果任一参数
  不正确的类型对应的转换规范,行为
  未定义。
  


Just wondering what happens when I use the wrong format specifier in C?

For example:

x = 'A';
printf("%c\n", x);
printf("%d\n", x);

x = 65;
printf("%c\n", x);
printf("%d\n", x);

x = 128;
printf("%d\n", x);

解决方案

what happens when I use the wrong format specifier in C?

Generally speaking, undefined behaviour.*

However, recall that printf is a variadic function, and that the arguments to variadic functions undergo the default argument promotions. So for instance, a char is promoted to an int. So in practice, these will both give the same results:

char x = 'A';
printf("%c\n", x);

int y = 'A';
printf("%c\n", y);

whereas this is undefined behaviour:

long z = 'A';
printf("%c\n", z);


* See for example section 7.19.6.1 p9 of the C99 standard:

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

这篇关于当我使用了错误的格式说明会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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