-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
  • 506,650
  • 124
  • 909
  • 1,183
booda
  • 9
  • What outputs did you expect? – Konrad Rudolph May 07 '19 at 21:02
  • 2
    `sizeof` needs a `%zu` format specifier. – Crowman May 07 '19 at 21:02
  • If you pass an argument of the wrong type to printf, then following args may not be aligned correctly. – stark May 07 '19 at 21:06
  • Explain what output you expected instead and why. – klutt May 07 '19 at 21:07
  • Please correct the compiler warnings. Also, `sizeof(a+d)` will give the size of the intermediate computation type. In all your examples, the first argument will need `%f` and the second will need `%zu`. – Weather Vane May 07 '19 at 21:07
  • 2
    You are producing undefined behavior by passing arguments to `printf()` that are mismatched with their corresponding formatting directives. There is nothing to understand here, beyond that C makes no guarantees about what the program will do. – John Bollinger May 07 '19 at 21:10
  • @Weather Vane: `%lf` is perfectly acceptable for the *first* argument, and I'd say `%lf` is even more appropriate here than `%f` (yes, I know that they are equivalent here). – AnT May 07 '19 at 21:18
  • @AnT but it was not, it was `%d` in the answer as first posted. FFS. – Weather Vane May 07 '19 at 21:19
  • @Weather Vane: `%d` makes no sense, of course. I'm just nothing that there's no need to replace `%lf` with `%f`. – AnT May 07 '19 at 21:20
  • @AnT sorry, I thought your comment was under the first (unedited) post of an answer, but anyway, the `%d` in the question is wrong. – Weather Vane May 07 '19 at 21:21

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
  • 49,231
  • 7
  • 69
  • 74