Friday, July 5, 2013

Printf with More Format Specifiers

We know that printf() function is responsible for printing something to the Output in C. Generally we write a printf() function with a string in it to be printed, or a string with format specifiers, followed by the variables which should take place of the format specifiers.

For example,


  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=5;
  5. printf("Hello\n");
  6. printf("Your number is %d", a);
  7. }
For the above program, the output turns out to be as

Hello
Your number is 5

But if it has more or less number of format specifiers, then what happens???

Let us know about that,

A printf() function is intended to take any number of arguments, to know about that, we can refer to the printf() section by clicking here

So, it can take more parameters, but a printf() function doesn't return any error if the number of parameters are more or less than the expected. Then what happens if we have more parameters???

Printf() with more parameters:

Consider the following program, 
  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=5,b=6;
  5. printf("Checking with more parameters\n");
  6. printf("The printed value is %d\n", a,b);
  7. printf("This is how it takes");
  8. }
The output of the above program is 

Checking with more parameters
The printed value is 5
This is how it works

So if a printf() has more parameters, it takes only the first occurrences of the values and leaves the remaining values.

Printf() with less parameters:

Consider the following program,

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=5;
  5. printf("Checking with less parameters\n");
  6. printf("The printed value is %d %d %d\n", a);
  7. printf("This is how it takes");
  8. }
The output of the above program turns out to be as,

Checking with less parameters
The printed value is 5 0 758
This is how it takes

Don't be confused about the values after 5. Those are the garbage values, they can be anything. They can differ from one running to another running. 

Thus a printf() function performs with different number of parameters. 

What happens if we change the format specifier for a variable???? To know, click here.