在 C 中的 if 语句中初始化变量?

Initializing a variable inside of an if-statement in C?

我不确定初始化变量 countinvFlag 的方式有什么问题。是否不允许在 if 语句中初始化变量?如果您想知道这是我的代码的一部分,用于检查我递归解决的迷宫是否正确(即检查是否有'.'给出的路径,它使我从开始 'S' 到结束 'E').迷宫在函数 solveMaze 中被正确解决,但这个函数只是检查它是否被正确解决。例如,我使用变量 invFlag 来确保我不会下去,然后再进行下一次调用,因为那将毫无意义)。一开始(当我在开始'S'时,我想像我一样将这个invFlag初始化为一个垃圾值)。这是代码的一部分。

我收到此错误:

maze.c: In function ‘checkMaze’:
maze.c:151: error: ‘count’ undeclared (first use in this function)
maze.c:151: error: (Each undeclared identifier is reported only once
maze.c:151: error: for each function it appears in.)
maze.c:152: error: ‘invFlag’ undeclared (first use in this function)
make: *** [maze.o] Error 1

我的部分代码:

int checkMaze(char ** maze, int width, int height, int x, int y)

if(maze[y][x] == 'S')
{
    int invFlag, count;
    invFlag = 4;     // junk value
    count = 0;
}

if(count <=15)
        printf("y: %d  x:  %d invFlag: %d \n", y, x, invFlag);

count = count+1;

if (maze[y][x] == 'E')
    return 1;

/* recursive calls (order: right, up, left, down) */

// if right of current position is '.' move there
if ( ( (maze[y][x+1] == '.') || (maze[y][x+1]  == 'E') ) && (invFlag != 2 ) ) 
{   
    invFlag = 0;    // right move will be performed
    checkMaze(maze, width, height, x + 1, y);
}

// if up of current position is '.' move there
else if ( (maze[y-1][x] == '.' || maze[y-1][x]  == 'E') && ( invFlag != 3) )
{
    invFlag = 1;    // up move will be performed
    checkMaze(maze, width, height, x, y - 1);
}

// if left of current position is '.' move there
else if ( (maze[y][x-1] == '.' || maze[y][x-1]  == 'E') && (invFlag != 0 ))
{   
    invFlag = 2;    // left move will be performed
    checkMaze(maze, width, height, x - 1, y);
}

// if down of current position is '.' move there
else if ( (maze[y+1][x] == '.' || maze[y+1][x]  == 'E') && (invFlag != 1 ))
{
    invFlag = 3;    // down move will be performed
    checkMaze(maze, width, height, x, y + 1);
}

return 0;  // maze solution was not correct
}

初始化不是问题,您在 if 块中 声明 它们,因此它们未在函数范围内声明,因此出现错误。

就搬这个

int invFlag, count;

if块之外到函数作用域,然后它会编译,它是否会起作用是另一回事,除非你确定不会,否则让变量未初始化是个坏主意是初始化之前的任何访问。

您似乎正在使用 gcc,如果您使用 -Wall 调用它,它会发出警告。

如果有另一个 invFlag 声明,则 if 块外的 invFlag 不是您在 if 块中声明的 invFlag ,在那种情况下只需删除声明,并使用 -Wshadow 使 gcc 对此发出警告。

变量count的可见性正好在if()块内

if()
{
  //count is visible within if
}

// count is unknown here

由于在 if() 块之外不知道计数,编译器报告错误,这可以通过将变量声明移到 if() 块之外来解决,例如

int count;

if()
{
  // count is visible
}
// count is visible