-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 
10
  • What outputs did you expect? Commented May 7, 2019 at 21:02
  • 2
    sizeof needs a %zu format specifier. Commented May 7, 2019 at 21:02
  • If you pass an argument of the wrong type to printf, then following args may not be aligned correctly. Commented May 7, 2019 at 21:06
  • Explain what output you expected instead and why. Commented May 7, 2019 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. Commented May 7, 2019 at 21:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It's undefined behaviour if the specifier is incorrect, regardless of the sizes of types
The first format specifier to match a + d must be %f.
@WeatherVane it can be %lf or %f (both have the same definition)
@M.M Yes, but not %d in the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.