• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Mock Exam Q

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which of the following implementations of a max() method will correctly return the largest value?
// (1)
int max(int x, int y)
{
return( if(x > y){ x; } else{ y; } );
}
// (2)
int max(int x, int y)
{
return( if(x > y){ return x; } else{ return y; } );
}
// (3)
int max(int x, int y)
{
switch(x < y)
{
case true:
return y;
default :
return x;
};
}

// (4)
int max(int x, int y)
{
if (x > y) return x;
return y;
}
The correct answer is no 4.
Doen't snippet 1 and 2 have the same meaning as 4.
Pls help, I am confused.
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No they do not.
The argument to return must be an expression, not a statement.
Ie, you return a value, like:
return 5;
or
return x*2;
or
return getValue();
Etc.
You can't "return" a statement:
return (while(true) { } ) ; //compiler error
And if statement, is a statement, not an expression. An expression is something you evaluate and obtain a value for. You merely execute a statement, it has no value.
 
Tanuja Vaid
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob, it's clear now!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic