In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?
Posted
by
DeveloperDon
on Programmers
See other posts from Programmers
or by DeveloperDon
Published on 2012-08-25T06:28:38Z
Indexed on
2012/11/06
17:21 UTC
Read the original article
Hit count: 206
c++
|coding-standards
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?
© Programmers or respective owner