In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?
- by DeveloperDon
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?