Exercise 5.7_c possible error.
Overload86 opened this issue · 2 comments
Overload86 commented
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;
emmanuelmoon commented
Yeah, "ival" doesn't register in the second if as it is out of scope.
Muhammad-Murtaazaa commented
ig the correct code should be
int ival = get_value();
if(ival){
cout<<"ival= "<<ival<<endl;
}
else{
cout<<"ival= '<<ival<<endl;
}