In C and C++, it is very easy to write the following code with a serious error.
char responseChar = getchar();
int confirmExit = 'y' == tolower(responseChar);
if (confirmExit = 1)
{
exit(0);
}
The error is that the if statement should have been:
if (confirmExit == 1)
As coded, it will exit every time, because the assignment of the confirmExit variable occurs, then confirmExit is used as the result of the expression.
Are there good ways to prevent this kind of error?
if (confirmExit). – Secure Aug 25 '12 at 07:16true) is dangerous. If, for some reason,confirmExithas the value 2, thenif (confirmExit == 1)is incorrect, butif (confirmExit)is correct. – Keith Thompson Aug 25 '12 at 09:14a = bora == binside a conditional. – Karl Bielefeldt Aug 25 '12 at 16:46if (confirmExit), and most expert C programmers would do that. – kevin cline Nov 06 '12 at 16:58