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

StackOverflow https://stackoverflow.com/questions/21659175

  •  09-10-2022
  •  | 
  •  

Question

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.

No correct solution

OTHER TIPS

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."

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.

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."

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top