Here are some typos I made that cannot be detected by the compiler and there seems to be no one clinical preventative method other than taking great caution when reviewing your code to avoid them.
(forever tbc)
Please comment on how you avoid typos like these and/or hidden typos that'll lead to disasters you've encountered. Thx!
auto fill error (mismatched function names)
//mismatched function name
void printTreeIn(const tptr root)
{
if (nullptr == root)
{
return;
}
printTreePre(root->m_left); //should be printTreeIn
printNode(root);
printTreeIn(root->m_right);
return;
}
This one can be avoided by overloading a function name to support varied but related applications. Not universally applicable, though.
auto fill error (mismatched varaible names)
auto-fill usually use the most commonly/recently used; or the closest token; do not "tab" too quickly, always keep an eye on what you actually typed.
tptr copyTree(tptr root)
{
if (nullptr == root)
{
return nullptr;
}
tptr cpy = new tn(root->m_val);
tptr curCpy;
queue<tptr> cpyq;
cpyq.push(cpy);
tptr curNode;
queue<tptr> q;
q.push(root);
while (!q.empty())
{
curNode = q.front();
q.pop();
curCpy = cpyq.front();
cpyq.pop();
if (nullptr != curNode->m_left)
{
curCpy->m_left = new tn(curNode->m_left->m_val);
curCpy->m_left->m_parent = curCpy;
q.push(curNode->m_left);
cpyq.push(curCpy->m_left);
}
if (nullptr != curNode->m_right)
{
curCpy->m_left= new tn(curNode->m_left->m_val); //!!! future segfault
curCpy->m_right->m_parent = curCpy;
q.push(curNode->m_right);
cpyq.push(curCpy->m_right);
}
}
return cpy;
}
habitual ";" very deadly :(
==> when the logics seem fine, check grammar
==> find all ");" and make sure none are of this disturbing nature.
void printTreePre(tptr root)
{
if (nullptr == root)
{
return;
}
stack<tptr> q;
tptr curNode;
q.push(root);
while (!q.empty())
{
curNode = q.top();
q.pop();
printNode(curNode);
cout << "check children.\n";
if (nullptr != curNode->m_right)
{
q.push(curNode->m_right);
printNode(curNode->m_right);
}
if (nullptr != curNode->m_left); //!!! the next{} will always be executed
{
q.push(curNode->m_left);
printNode(curNode->m_left);
}
cout << endl;
}
cout << endl;
return;
}

本文探讨了编程中常见的错误,如自动填充导致的函数名和变量名不匹配,这些错误可能逃过编译器的检查。作者分享了如何通过细心审查、重载函数名以及养成良好的编程习惯来防止这类问题。同时,提醒程序员在逻辑看似正确时,仍需检查语法,确保没有遗漏的分号导致的逻辑错误。
221





