我在函数内的第一个返回值没有返回任何东西
问题描述:
所以我有一个控制玩家转向的函数,我希望它在玩家转弯失败时返回FAILURE。 (游戏连接4)。我很明显希望它在回合成功时能够成功,但是......即使当我返回成功时,也需要两次返回成功才能返回一次成功。下面是代码:我在函数内的第一个返回值没有返回任何东西
enum input_result take_turn(struct player * current,
enum cell_contents board[][BOARDWIDTH])
{
/***************** Logic for Human player ******************/
if(current->type == HUMAN)
{
printf("human");
return SUCCESS;
}
/**************** Logic for Computer player ****************/
else if(current->type == COMPUTER)
{
printf("computer");
return SUCCESS;
}
return SUCCESS;
}
而且它是由这家名为:
struct player * play_game(struct player * human ,
struct player* computer)
{
while(counter < 30)
{
take_turn(current, board);
/* Only swap if take turn was success */
if(take_turn(current, board) == SUCCESS)
{
swap_players(¤t, &other);
display_board(board);
}
counter++;
}
return NULL;
}
我觉得可能毁掉这样做的唯一的事情就是我的:
enum input_result
{
/**
* the input was valid
**/
SUCCESS,
/**
* the input was not valld
**/
FAILURE,
/**
* the user requested to return to the menu either by pressing enter on
* an empty line or pressing ctrl-d on an empty line
**/
RTM=-1
};
我不确定为什么take_turn(current,board)被调用两次,当唯一可能的结果是输入if语句时,因为每个可能的返回值都是SUCCESS。有谁知道为什么会发生这种情况? 我的输出打印:
HumanHuman
ComputerComputer
HumanHuman
ComputerComputer
等等...这表明它经历了两次被注册成功了。
答
你的问题是在这里:
while(counter < 30)
{
take_turn(current, board);
/* Only swap if take turn was success */
if(take_turn(current, board) == SUCCESS)
你打电话take_turn()
两次。
只是为了澄清:你想知道为什么'take_turn'仍然在if子句中执行,尽管它只能返回'SUCCESS'并且if子句中的代码**必须被执行? – Downvoter
是的,我想知道为什么它没有进入if语句,并且在返回唯一可能的返回值时调用玩家交换是成功的 – Rrr
我已经投票决定关闭这个问题,因为这个问题不能成为印刷错误重复(一旦OP删除额外的呼叫'take_turn()'。 – mah