Question

I find this code , see, the printf has only one param.And, it work! All I kown about printf is printf("format",...); but why this code work? Any answer will help . Thanks.

  1 #include <stdio.h>
  2 
  3 int main()
  4 {
  5         char a[]= "hello world";
  6         printf(a);
  7         return 0;
  8 }
~           
Was it helpful?

Solution

a is the format. However, this kind of usage is very dangerous because lots of people forget that a is a format and instead think it's a literal string. The difference is that, if a happened to contain %, it would be interpreted as a format specifier, but you have no arguments for to specifier to go with.

When printing a single message string with printf, you should always instead do:

printf("%s", a);

Or just use puts if appropriate.

OTHER TIPS

a is being treated as a format string that contains no format specifiers.

Normally, printf() will scan the format string, print anything that isn't a format specifier. When it encounters a specifier, it decodes it, then takes an argument from the variable argument list, formats it according to the specifier, and outputs that, then continues like that in a loop until it reaches the end of the string.

Since a contains no format specifiers, printf() takes no arguments from the variable argument list.

Generally speaking, printf() should not be used to print arbitrary strings in this way. If the program is only printing a string, you can use fputs() instead:

fputs(a, stdout);

printf is a function with variable list of parameters. The first parameter is a string that is parsed to find the formatting details. In the example you gave, there is no formatting detail (fields starting with %). Hence, there is no more parameters to be printed and the code works.

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

Is a function with a required argument, format and a list argument that can be a list or zero or more elements, represented by ....

Thus, printf(a); is simply a call to printf() with only the required argument.

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