What is the output of the following code written in C? void main() {…
2021
What is the output of the following code written in C?
void main()
{
printf("%d%d%d", 62, 062, 0x62);
}Answer: C. 625098 — Concept. In C the prefix of an integer literal decides the base in which that literal is read, while the %d conversion always prints the stored value in…
- A.
506298
- B.
629850
- C.
625098
- D.
986250
Attempted by 1777 students.
Show answer & explanation
Correct answer: C
Concept. In C the prefix of an integer literal decides the base in which that literal is read, while the %d conversion always prints the stored value in ordinary decimal. A prefix therefore changes how a constant is written and understood — never how it is displayed.
A digit string with no prefix is decimal (base 10); a leading 0 marks an octal literal (base 8); a leading 0x marks a hexadecimal literal (base 16). printf also consumes its arguments strictly from left to right, one argument per conversion specifier.
Applying it to this code.
The literal
62carries no prefix, so it is read in base 10 and its stored value is 62.The literal
062begins with0, so it is read in base 8: (6 × 81) + (2 × 80) = 48 + 2 = 50.The literal
0x62carries the0xprefix, so it is read in base 16: (6 × 161) + (2 × 160) = 96 + 2 = 98.The three
%dspecifiers take these three arguments in the order they are written, and the format string"%d%d%d"puts no space or separator between them, so the three printed decimal strings run together.
Literal | Prefix | Base it is read in | Value printed by %d |
|---|---|---|---|
| none | decimal (base 10) | 62 |
|
| octal (base 8) | 50 |
|
| hexadecimal (base 16) | 98 |
Cross-check. Converting back the other way confirms both readings: 50 written in base 8 is 62, which is exactly the literal 062; and 98 written in base 16 is 62, which is exactly the literal 0x62. The three printed values are 62, 50 and 98; what fixes the sequence in which they appear is printf reading its arguments from left to right.
Output. The program prints 625098.
Note: void main() is not standard C — portable programs declare int main(void) — but that does not change the values printed here.