Sunday, December 9

Mastering printf() #1

The function printf() is one of the widely used functions in C-language.This is a standard output function defined in header stdio.h. It takes variable number of arguments.
The proper declaration of printf is

int printf(char *format, arg1,arg2,...)

printf converts ,formats,and prints its arguments on the the standard output.
return value: Number of characters printed.


Even though this is a basic function one uses in C, many people tend to neglect the above details!

Consider the following program

#include<stdio.h>
main()
{
int i = 98765;
printf("%d\n",printf("%d",printf("%d",i)));
}

What do you think the out put will be?
Output: 98765 5 1(outputs are spaced for the sake of clarity).

Remember that return value of printf is "Number of characters printed on to the screen"

So in the above output ,
The innermost printf: printf("%d",i) -- prints the ivalue(i.e 98765),returns the value 5
The second innermost printf: printf("%d ",printf("%d ",i)) -- prints value 5,returns 1
The outer printf -- prints the value 1.

Have look at the following program

#include<stdio.h>
main()
{
int i = 10;
printf(" %d %d %d \n", ++i, i++, ++i);
}

What do u reckon the output will be??
13 11 11? this could be one possible answer!
Yes, because the expression evaluation inside printf function is 'Compiler Dependant'.
Some compilers evaluate the expressions from right to left (Thats when you get the above answer 13 11 11). Some have its own evaluation procedure!

No comments: