【问题标题】:C - Passing a local variable in a function without initializingC - 在函数中传递局部变量而不初始化
【发布时间】:2016-09-20 20:08:19
【问题描述】:

所以我真的很陌生,我想知道如何在函数中传递局部变量(就初始化而言)。例如,我有一个函数(move),它声明和初始化两个变量(t_row 和 t_column)以用于 for 循环,在该循环中,我有另一个函数(swap),如果满足某些条件,则调用它.如何在交换函数中使用这些变量。我知道我需要声明它们,但是它们在交换函数中的初始化取决于调用了 for 循环交换的迭代。提前感谢您的帮助!

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;
}

【问题讨论】:

  • Calling a local variable...嗯。
  • 如果你传入它们,就使用它们。

标签: c variables local initializing


【解决方案1】:

我能看到的最简单的方法是传入旧行和列的值。

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;
}

【讨论】:

  • 好的,谢谢。我正在考虑这样做,但这似乎是多余的,因为每次我调用它时 row_old 和 row_new 都是同一个变量,而且我实际上最终调用了它几次,但这很有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多