我正在尝试在函数中使用递归,为此我必须使用局部变量。编译器在我定义本地变量的行中给出了错误c141。
int minimax(int board[9], int player) {
int winner;
winner = win(board);
if (winner != 0) return winner*player;
int moveminimax;
moveminimax = -1;
int scoreminimax;
scoreminimax = -2;
int i3;
for (i3= 0; i3 < 9; ++i3) {//For all moves,
if (board[i3] == 0) {//If legal,
board[i3] = player;//Try the move
int thisScore;
thisScore = -minimax(board, player*-1);
if (thisScore > scoreminimax) {
scoreminimax = thisScore;
moveminimax = i3;
}board[i3] = 0;//Reset board after try
}
}
if (moveminimax == -1) return 0;
return scoreminimax;
}
6-3-17 4 01pm.c(116): error C141: syntax error near 'int'
//c(116) is the where int winner is defined
当我在程序开头全局定义我的变量时,错误就会消失。
答案 0 :(得分:3)
我的猜测是Keil C编译器没有遵循C99标准,其中变量可以在任何地方定义,而是遵循旧的C89标准,其中局部变量只能在开头定义块。
这意味着像
这样的代码int winner;
winner = win(board);
if (winner != 0) return winner*player;
int moveminimax;
moveminimax = -1;
int scoreminimax;
scoreminimax = -2;
int i3;
无效,因为它包含混合声明和语句。
通过在声明变量时初始化变量,可以完全删除其中两个语句,这会留下需要移动的函数调用和if
语句。
请改为尝试:
int winner;
int moveminimax = -1;
int scoreminimax = -2;
int i3;
winner = win(board);
if (winner != 0) return winner*player;