LearnFrenzy
Sign in Take a free test

Data Types · Find the Error · Question 1

Printing a double with %d in C Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    double price = 99.5;
    printf("Price: %d\n", price);
    return 0;
}
  • A price must be a float
  • B printf cannot print doubles
  • C There is no bug; it prints 99
  • D %d expects an int but a double is passed – undefined behaviour; use %f or %.2f Correct
Correct Answer: Option D

printf trusts the format string. On x86-64 and ARM64 a double travels in a different register than an int, so %d prints garbage – it never converts. -Wall warns about the mismatch.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links