Programming Fundamentals · Interview question

What does int avg = 5 / 2; give you, and why?

A strong answer

avg ends up as 2, not 2.5. Both operands of / are int, so C performs integer division and truncates the fractional part before the result reaches the assignment. The ordering is the part people miss: the division happens first and produces 2, so declaring avg as float doesn't help either, you'd get 2.0f, not 2.5f. The fix is to make at least one operand floating-point so the usual arithmetic conversions promote the other, 5 / 2.0f or 5.0f / 2. Casting one operand works the same way, (float)a / b, and note (float)(a / b) does not, it casts the already-truncated result. This bites hardest with variables rather than literals, because int sum, count; float avg = sum / count; looks obviously correct and silently isn't. On embedded there's a wrinkle worth raising unprompted: integer division is often the right choice, since many microcontrollers have no FPU and float math becomes slow library calls, and some Cortex-M cores lack a hardware divide instruction entirely. The idiomatic fix there is fixed-point, scale up first and divide once, as in (sum * 100) / count to keep two decimal places in an integer, being careful the multiply doesn't overflow the type.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Variables & Data Types

Named boxes that hold a value. Pick a type, declare, assign, and learn why C makes you say what kind of thing each box holds.

More Variables & Data Types questions

Browse all 472 interview questions
What does int avg = 5 / 2; give you, and why? | EmbeddedPrep.io