【发布时间】:2013-01-11 01:10:55
【问题描述】:
这更像是一个入门级问题,但我想知道使用空 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 语句什么都不做会被认为是不好的做法。我知道我可以回来;
但由于我的返回类型是 void,它给了我一个错误。例如,如果我的返回类型不是 void 怎么办?
【问题讨论】:
-
这是一个风格问题,本质上是主观的。但是一个好的经验法则是永远不要在你的代码库中放置注释掉的代码。
-
@Oli 感谢您的回答。我是自学的,所以由于我没有直接的指导,我还是更喜欢问这类问题。
-
附带说明:现在不推荐使用宏
NULL,更喜欢使用nullptr,请参阅 stackoverflow.com/questions/1282295 和 stackoverflow.com/questions/13816385 -
甚至可以将“head”条件放在 for 循环中
-
我很想对这个问题发表一个空洞的答案。
标签: c++ if-statement