Reputation: 57
One very experienced programmer wrote something like this:
#include <string>
using namespace std;
class Fraction
{
float nominator;
float denominator;
void load()
{
cin>>nominator; cin>>denominator;
if(denominator==0)
{
while(denominator==0)
{
cout<<"denominator can not be equal 0!"<<endl;
cin>>denominator;
}
}
}
};
I have no idea why there is an if statement. Is it really necessary?
Upvotes: 2
Views: 599
Reputation: 11
From this code:
if(denominator==0)
{
while(denominator==0)
{
cout<<"denominator can not be equal 0!"<<endl;
cin>>denominator;
}
}
I think if
is only used for a teaching purpose to simply show that how flow will go to while
after checking if condition. And how while loop
will work further.
But if is not really required here. This code do the same:
while(denominator==0)
{
cout<<"denominator can not be equal 0!"<<endl;
cin>>denominator;
}
Upvotes: 0
Reputation: 238461
Is it really necessary?
No, it is not necessary.
The shown snippet is equivalent to a program where the if statement is replaced with the contained loop statement.
Upvotes: 0
Reputation: 40150
In this particular example,
while(denominator==0)
{
cout<<"denominator can not be equal 0!"<<endl;
cin>>denominator;
}
would be exactly equivalent.
In the context you provided, nothing can tell us why someone would nest that loop in an useless if
, but one could come up with explanations. In earlier version of that code, something could have been present inside the if
block that changed the behavior of the program/function.
It also could be an innocent error.
Stroustrup's cat might have walked on their keyboard.
Upvotes: 4