In C++ (assignment in a conditional), analyze the following program and determine what is printed by Display(). Note the deliberate use of "if (l = 0)" vs "if (l == 0)". #include<iostream.h> class AreaFinder { float l, b, h; float result; public: AreaFinder(float hh = 0, float ll = 0, float bb = 0) { l = ll; b = bb; h = hh; } void Display(int ll) { if(l = 0) result = 3.14f * h * h; else result = l * b; cout << result; } }; int main() { AreaFinder objAF(10, 10, 20); objAF.Display(0); return 0; }

Difficulty: Easy

Correct Answer: 0

Explanation:


Introduction / Context:
This question spotlights a classic C/C++ bug: using assignment (=) instead of comparison (==) inside an if condition. It also asks you to trace how that bug changes the path and, consequently, the computed result in a simple area calculation scaffold.


Given Data / Assumptions:

  • Constructor call is AreaFinder(10, 10, 20) so h=10, l=10, b=20.
  • In Display, the line if (l = 0) assigns 0 to l and yields false.
  • Therefore the else block executes with l already changed to 0.


Concept / Approach:
In C++, assignments in boolean contexts evaluate to the assigned value. Here, l = 0 makes l zero and the condition evaluates to false, forcing execution into the else branch. Since l was just set to zero, result = l * b becomes 0 regardless of b.


Step-by-Step Solution:

Initial: l = 10, b = 20, h = 10 Condition: if (l = 0) → assigns 0, evaluates false Execute else: result = l * b = 0 * 20 = 0 cout prints 0


Verification / Alternative check:
If the code had been if (l == 0), the if would be false and the else would compute 10 * 20 = 200. If the intention was circle area, the branch should check a flag parameter instead of clobbering l.


Why Other Options Are Wrong:

  • 314 / 314.0000: Would require entering the circle-area branch.
  • 200.0000: Would need to keep l=10 before multiplication.


Common Pitfalls:
Overlooking side effects from assignment in conditions and assuming the variable value remains unchanged when the if is false.


Final Answer:
0

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion