can there be less number of fomat specifier than the number of variables in a printf statement

痞子三分冷 提交于 2019-12-14 02:48:00

问题


I have coded the following program in a borland c compiler.My doubt is why c compiler doesnot throw any error neither in compile time or run time.The program executes fine and the output is 2 4.

#include<stdio.h>
#include<conio.h>
int main(){
int a=2,b=4,c=6;
printf("%d%d",a,b,c);
getch();
return 0;
}

Even though there are less no of format specifiers than the number of arguments there is no error thrown.What is happening here.


回答1:


can there be less number of fomat specifier than the number of variables in a printf statement

Answer is yes. From the C Standard:

(c99, 7.19.6.1p2) "If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored."




回答2:


That will work fine but may give a compiler error if your compiler is set to check printf varargs parameters.

The printf function is variadic, i.e. takes a variable number of arguments. The format string will dictate how many are used, and if you specify too many they will be ignored. The POSIX reference is: http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html which states:

If the format is exhausted while arguments remain, the excess arguments shall be evaluated but are otherwise ignored.

(the underlying C reference is C 2011 7.21.6.1 2 from http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf - thanks @EricPostpischil - but that's a 701 page PDF)

That is, however, rather obvious from how variadic functions work.

The opposite (having fewer variables than in your format specifier) is not permissible as the printf function will attempt to access variables that are not present on the stack, giving undefined behaviour.




回答3:


Yes.

http://www.cplusplus.com/reference/cstdio/printf/

"There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function."




回答4:


Though you have provided three variables to printf() but only two format specifiers are there, so those two are replaced with the first two available variables.




回答5:


Because you have function that accepts a variable number of arguments

int printf ( const char * format, ... );

In C, it's mean that there is no arguments type checking and, even more, printf does not know how much arguments user pass to the function. There is a trick - printf counts the number of % and decide that it's the number of arguments. To understand how it work you can look to the va_list, va_start , va_end, va_arg. Try to run printf("%i,%i,%i", a); - Undefined Behavior.



来源:https://stackoverflow.com/questions/21659175/can-there-be-less-number-of-fomat-specifier-than-the-number-of-variables-in-a-pr

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