1

so I'm really new at this, and I was wondering how I would go about passing a local variable in a function (in terms of the initialization). For example, I have one function (move) that declares and initializes two variables (t_row and t_column) to be used in a for loop, and within that loop, I have another functions (swap), that is called if certain conditions are met. How do I go about using those variables in the swap function. I know I need to declare them, but their initialization in the swap function depends on what iteration of the for loop swap was called. Thanks in advance for any help!

bool move(int tile)
{
    for (int t_row = 0; t_row < d; t_row++)
    {
        for (int t_column = 0; t_column < d; t_column++)
        {
            if (tile == board[t_row][t_column])
            {
                if (0 < t_row && board[t_row - 1][t_column] == 0)
                {
                    swap(t_row - 1, t_column);
                    return true;
                }
            }
        }
    }
        return false;
}

void swap(int row_new, int column_new)
{
    int t_row;
    int t_column;        
    int hold = board[t_row][t_column];
    board[t_row][t_column] = 0;
    board[row_new][column_new] = hold;
}
Allie H
  • 121
  • 1
  • 11

1 Answers1

3

The easiest way I can see to do this would be to pass in the values of the old row and column.

void swap(int row_new, int col_new, int row_old, int col_old) {
    int hold = board[row_old][col_old];
    board[row_old][column_old] = 0;
    board[row_new][column_new] = hold;
}
heron
  • 121
  • 3
  • 1
    Yes, thank you. I was considering doing that, but it just seemed redundant since the row_old and row_new would be the same variable every time I called it, and I actually end up calling it a few times, but that works. Thank you! – Allie H Sep 20 '16 at 20:35