这是一个入门级问题,但我想知道是否有空if语句是良好的编程实践。
考虑以下代码:
考虑以下代码:
void RabbitList::purge()
{
if(head == NULL)
{
//cout << "Can't purge an empty colony!" << endl;
}
else
{
//Kill half the colony
for(int amountToKill = (getColonySize()) / 2; amountToKill != 0;)
{
RabbitNode * curr = head;
RabbitNode * trail = NULL;
bool fiftyFiftyChance = randomGeneration(2);
//If the random check succeeded but we're still on the head node
if(fiftyFiftyChance == 1 && curr == head)
{
head = curr->next;
delete curr;
--size;
--amountToKill;
}
//If the random check succeeded and we're beyond the head, but not on last node
else if(fiftyFiftyChance == 1 && curr->next != NULL)
{
trail->next = curr->next;
delete curr;
--size;
--amountToKill;
}
//If the random check succeeded, but we're on the last node
else if(fiftyFiftyChance == 1)
{
trail->next = NULL;
delete curr;
--size;
--amountToKill;
}
//If the random check failed
else
{
trail = curr;
curr = curr->next;
}
}
cout << "Food shortage! Colony has been purged by half." << endl;
}
}
正如您所看到的,第5行上的if语句目前已被注释掉; 这只是一个调试文本,我不想再向控制台发送任何反馈。我相信让if语句什么也不做会被认为是不好的实践。我知道我可以使用return;来解决这个问题。
但是,由于我的返回类型是void,它会给我一个错误。如果我的返回类型不是void呢?
NULL
已经被弃用,建议使用nullptr
,请参阅https://dev59.com/b3M_5IYBdhLWcg3wq1CF和https://dev59.com/jGYr5IYBdhLWcg3wQYJa。 - kebs