Home > OS >  The output of the above C Language code is Rs.10.008 but why?
The output of the above C Language code is Rs.10.008 but why?

Time:12-31

The output of the above C Language code is Rs.10.008 but why ?????

#include<stdio.h>
    int main(){
        unsigned i = 10;
        i = printf("Rs.%d.00",i);
        printf("%d",i);
        return 0;
    }

CodePudding user response:

This statement:

i = printf("Rs.%d.00",i)

prints Rs.10.00 and returns 8 to indicate the number of characters printed. Notice that you are assigning the return value of printf to i.

Hence, the subsequent printf statement:

printf("%d",i);

Will now print 8 instead of 10. The first printf statement didn't specify an end-of-line char (\n), so it just concatenates the 8 onto the same line.

CodePudding user response:

Your code has undefined behavior as you use %d for printing unsigned int. You need to use %u for unsigned (int) and %d for (signed) int.

If that is fixed we have...

For printf the C standard says:

Returns

The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

So

int i = 10;   // Note unsigned changed to int
i = printf("Rs.%d.00",i);

will print "Rs.10.00" and set i to 8 because "Rs.10.00" is 8 characters long.

Then

printf("%d",i);

will print "8" so that the total output is "Rs.10.008"

CodePudding user response:

printf() return the number of characters that are printed, since your code is printing 8 characters so the value assigned to i after executing first printf is 8, and since new line is not added before second printf its printing the value of i in same line resulting in Rs.10.008

first printf is printing the value of i that is 10

i=printf("Rs.%d.00",i) // it prints Rs.10.00 and assign the value of i=8
  •  Tags:  
  • c
  • Related