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)
.a = b
ora == b
inside a conditional.