What happens when I use the wrong format specifier?

别说谁变了你拦得住时间么 提交于 2019-11-25 22:29:41

问题


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);

回答1:


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.




回答2:


since x is A, the first print f will print: 'A'.

The second will print the ascii value of A (look it up).

The 3rd one will print the ascii character for 65 (I think this is A or a, but its a letter).

The fourth one will print 65.

The 5th one will print 128.



来源:https://stackoverflow.com/questions/16864552/what-happens-when-i-use-the-wrong-format-specifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!