Connecting Tech Pros Worldwide Help | Site Map

problem with if statement

Member
 
Join Date: May 2007
Posts: 65
#1: Sep 25 '07
whats wrong with this function:

Expand|Select|Wrap|Line Numbers
  1. int max(int x, int y) {
  2.     return (if (x > y) { return x; } else { return y; });
  3. }
i get an "expected an expression" error
zodilla58's Avatar
Expert
 
Join Date: Dec 2006
Posts: 782
#2: Sep 25 '07

re: problem with if statement


Use this instead:

Expand|Select|Wrap|Line Numbers
  1. int max(int x, int y)
  2. {
  3.     if (x > y)
  4.         return x; 
  5.     else
  6.         return y;
  7. }
Regards
Member
 
Join Date: May 2007
Posts: 65
#3: Sep 25 '07

re: problem with if statement


Quote:

Originally Posted by zodilla58

Use this instead:

Expand|Select|Wrap|Line Numbers
  1. int max(int x, int y)
  2. {
  3.     if (x > y)
  4.         return x; 
  5.     else
  6.         return y;
  7. }
Regards

thanks for the reply.
i know that there are many alternative ways to perfom that functionality.
what i want to figure out is the rule which doesnt allow the above code to be considered as legal
zodilla58's Avatar
Expert
 
Join Date: Dec 2006
Posts: 782
#4: Sep 25 '07

re: problem with if statement


Quote:

Originally Posted by stmfc

thanks for the reply.
i know that there are many alternative ways to perfom that functionality.
what i want to figure out is the rule which doesnt allow the above code to be considered as legal

Your function has return type int. In your previous code, you have taken return withing return like:

Expand|Select|Wrap|Line Numbers
  1. return(if(...) return x; else return y;) 
That is not proper way to return the value.
dmjpro's Avatar
Lives Here
 
Join Date: Jan 2007
Location: India (West-Bengal)
Posts: 2,451
#5: Sep 25 '07

re: problem with if statement


Quote:

Originally Posted by stmfc

whats wrong with this function:

Expand|Select|Wrap|Line Numbers
  1. int max(int x, int y) {
  2.     return (if (x > y) { return x; } else { return y; });
  3. }
i get an "expected an expression" error

Try it.
Expand|Select|Wrap|Line Numbers
  1. return x>y?x:y;
  2.  
Kind regards,
Dmjpro.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#6: Sep 25 '07

re: problem with if statement


Quote:

Originally Posted by stmfc

whats wrong with this function:


Code: ( text )
int max(int x, int y) {
return (if (x > y) { return x; } else { return y; });
}


i get an "expected an expression" error

The function has an int return type so you have to return an int. That means the code between the parentheses must evaluate to an int. It doesn't.

The key is in the "expected an expression" reported by the compiler. An expression must evaluate to true or false where false is 0 and true is not false.

if statements don't have a value.
Reply