Mooophy / Cpp-Primer

C++ Primer 5 answers
Creative Commons Zero v1.0 Universal
8.11k stars 3k forks source link

Exercise 5.7_c possible error. #762

Open Overload86 opened 4 years ago

Overload86 commented 4 years ago
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 2 years ago

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

Muhammad-Murtaazaa commented 2 months ago

ig the correct code should be

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