Question

Can someone explain what the use/meaning is of the following return statement: t > 1; (see last if statement last method)

the code is from a game called "Reversi" http://en.wikipedia.org/wiki/Reversi

This method checks if you enclose a stone of another player.

public bool allowed(int x, int y, bool player)
    {
        int color;

        if(player == true) // true = player is blue.
            color= 1; 
        else color= -1;

        if(stone[x,y] != 0)
            return false;
        else
        {
         for (int dx = -1; dx <= 1; dx ++)
            {
             for (int dy = -1; dy <= 1; dy ++)
             {
                 if (dx != 0 || dy != 0) // 0, 0 must be skipped, own stone.
                 {
                     if (close(color, x, y, dx, dy))
                         return true;
                 }
             }
            }   
        }
         return false;
         }




public bool close(int color, int x, int y, int dx, int dy)
        {
            int s;
            int testx;
            int testy;
            for(int t=1; t<stone.Length;t++)
            {
                testx = x + t * dx;
                testy = y + t * dy;
                if(testx >= board.Width || testx <= 0 || testy >= board.Heigth|| testy <= 0)
                    return false;
            s = stone[x + t * dx, y + t * dy];
            if (s == 0) return false;
            if (s == color) return t>1;
        }
        return true;
    }
Was it helpful?

Solution

This code:

return t > 1;

Is equivalent to:

if (t > 1)
{
    return true;
}
else
{
    return false;
}

Except the latter approach is unnecessarily verbose and unfortunately quite common to see in real code.

OTHER TIPS

Any expression to the right of a return statement is evaluated, and then the value is returned from the function.

In this case, t can either be greater than 1, or not - meaning it's either true or false - meaning either true or false will be returned, depending on the value of t.

It's exactly equivalent to:

if(t>1)
    return true;
else
    return false;

Returns true if t is greater than 1, otherwise it returns false.

return t > 1;

is same as

if (t > 1)
   return true;
else
   return false;

is same as

bool greaterThanOne;

if (t > 1)
   greaterThanOne = true;
else
   greaterThanOne =false;

return greaterThanOne;

return t>1 is equal to

    if (t > 1)
   {
       return true;
   }
    else
   {
       return false;
   }

Also there is an another using of return like;

static string AmIAwesome(bool b)
        {
            return b ? "Yes, I'm" : "No, I'm not";
        }

Which is the same logic with first one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top