What will be the output of the following program? int a = 5; cout << "FIRST "…
2023
What will be the output of the following program?
int a = 5;
cout << "FIRST " << a<<2 << "SECOND";
- A.
FIRST 52 SECOND
- B.
FIRST 20 SECOND
- C.
SECOND 25 FIRST
- D.
More than one of the above
- E.
None of the above
Attempted by 213 students.
Show answer & explanation
Correct answer: E
Concept: In C++, the operator << is overloaded. When its left operand is a stream object such as cout, << means STREAM INSERTION — it prints the right operand as text and returns the stream so the next << can chain onto it. This is different from the BITWISE LEFT-SHIFT <<, which applies only when BOTH operands are plain integers on their own (for example, a standalone 5 << 2 equals 20).
Chained << calls associate left to right, and whitespace never changes tokenization, so a<<2 and a << 2 are exactly the same two tokens (<< then 2). Once the chain already starts from cout, every later << in that same chain is stream insertion, not bit-shift.
Application: Trace cout << "FIRST " << a << 2 << "SECOND"; left to right, with a = 5:
cout << "FIRST "printsFIRST(with its trailing space) and returnscout.<< aprints the value ofa, i.e.5→ output so far:FIRST 5<< 2is stream insertion (the left operand is the stream returned above, not a bare int), so it prints the literal2, not a shifted value → output so far:FIRST 52<< "SECOND"appendsSECONDwith no separating space → final output: "FIRST 52SECOND"
Cross-check against the options:
"FIRST 52 SECOND" inserts an extra space before SECOND that the code never produces.
"FIRST 20 SECOND" would only hold if
a << 2were read as the bitwise shift 5 << 2 = 20 — but the left operand here is a stream, not a bare int, so that reading does not apply."SECOND 25 FIRST" reverses both the print order and the digit order, contradicting left-to-right stream evaluation.
Since none of the three specific strings equal "FIRST 52SECOND", "more than one of the above" cannot hold either.
Correct Answer: None of the above