-1

I'm trying to understand how it's working.

#include<stdio.h> 
int main() 
{ 
    int a = 110; 
    double d = 10.21; 
    printf("sum  d: %d  \t\t size  d: %d \n", a+d, sizeof(a+d)); 
    printf("sum lf: %lf \t size lf: %lf \n", a+d, sizeof(a+d)); 
    printf("sum lf: %lf\t size  d: %d \n", a+d, sizeof(a+d)); 
    printf("sum  d: %d \t\t size lf: %lf \n", a+d, sizeof(a+d)); 
    return 0; 
}  

The output is:

sum  d: 8        size  d: 1343288280 
sum lf: 120.210000   size lf: 0.000000 
sum lf: 120.210000   size  d: 8 
sum  d: 8        size lf: 120.210000
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
booda
  • 9

1 Answers1

1

printf reads a certain number of bytes off the stack for each of the format specifiers you provide. The format specifiers must match the actual arguments or you can end up with arguments being partially read or reads going past the boundaries of the argument.

In your first statement, the first argument is a double so %f is the correct format specifier. Using %d may result in printf attempting to read more bytes than were provided for that argument, leading to undefined behavior. The second argument is of type size_t which requires %zu or another valid specifier for that type.

jspcal
  • 50,847
  • 7
  • 72
  • 76