0
{   
int a,b,c,d,e;
float percentage;

cout<<"marks= ";
cin>>a;
cin>>b;
cin>>c; 
cin>>d;
cin>>e;

percentage= (a+b+c+d+e)/5;
cout<<"Percentage= "<<percentage<<endl;

if (percentage<40)
cout<<"fail";

else if (percentage>=40,percentage<=49)
cout<<"third division";

else if (percentage>=50,percentage<=59)
cout<<"second division";

else if (percentage>=60)
cout<<"first division";

}

When i submit this to my lecturer, he said that it is theoretically wrong to use comma in the condition, and is suppose to be &&. However, I have successfully run this program. Can anyone explain to me?

Jephefnie Goh
  • 13
  • 1
  • 4

2 Answers2

2

It's simple logic. Let's start from the beginning.

if (percentage<40)
cout<<"fail";
else ...

Let's stop at this point.

If percentage is less than 40, this branch is taken. The End. Full Stop.

But then, under which conditions will we to get to this else part, then?

... if (percentage>=40,percentage<=49)
     cout<<"third division";

Well, we can only get here if percentage is not less than 40, or percentage >= 40. If percentage was less than 40, the first if statement will evaluate to true. But if execution reaches the second if statement, we must logically conclude that the first comparison must always be true, so it is completely meaningless. If this if statement was written "correctly" (for some generic definition of "correctly":

  if (percentage>=40 && percentage<=49)
     cout<<"third division";

Then the first comparison will always evaluate to true, because the only way you can get here is if percentage>=40, otherwise you wouldn't get here, so this is logically equivalent to, in this case, to:

  if (percentage<=49)
     cout<<"third division";

And with your mistake of using the comma operator, the first comparison also gets thrown away completely, and you still end up here. Which is why you're getting correct results. But for slightly wrong reasons.

The remaining if statements end up with the same fate.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

In the absence of operator overloading (which is utterly not recommended for the comma operator), the comma operator evaluates but ignores the result of the LHS of the operator, so the tested conditions on the LHS are pointless. They're also excluded by the prior if conditions. For example, the first if is percentage<40; execution will only get to else if (percentage>=40,percentage<=49) if the value in percentage is 40 or more, so the test on the LHS of the comma is pointless again.

However, that is why the code works. The earlier if tests exclude the cases that the ignored operations on the LHS of the comma operator attempt to test for.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278