Mooophy/Cpp-Primer

Exercise 5.7_c possible error.

Overload86 opened this issue · 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;

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

ig the correct code should be

int ival = get_value();
if(ival){
cout<<"ival= "<<ival<<endl;
}
else{
cout<<"ival= '<<ival<<endl;
}