Cpp-Primer icon indicating copy to clipboard operation
Cpp-Primer copied to clipboard

Exercise 5.7_c possible error.

Open Overload86 opened this issue 4 years ago • 2 comments

if (int ival = get_value())
    cout << "ival = " << ival << endl;
if (!ival)     
    cout << "ival = 0\n";

What you wrote is probably also true, but the more glaring error to me is, that ival is defined inside the "if" condition. After the first if ends with 'cout'ing the string, the variable will lose it's scope and the second if cannot evaluate it's condition, or am I mistaken? (Same if you change it to an else/if.

So the correct code should be:

int ival = get_value();
if (ival)
   cout << "ival = " << ival << endl;
else
   cout << "ival = 0" << endl;

Overload86 avatar Jul 12 '20 03:07 Overload86

Yeah, "ival" doesn't register in the second if as it is out of scope.

emmanuelmoon avatar Jul 18 '22 12:07 emmanuelmoon