Using the wrong operator can result in subtle bugs and incorrect program behavior that may be difficult to detect through testing. Carefully choosing the correct operator and following language best practices around operator usage can help mitigate this weakness.
1
2void useOfIncorrectOperatorNoncompliant() {
3 char *src, *dst;
4 int left;
5
6 while (*src && left) {
7 *dst++=*src++;
8 // Noncompliant: Used assignment instead of equality operator.
9 if (left = 0) {
10 die("badlen");
11 }
12 left--;
13 }
14}
1
2void useOfIncorrectOperatorCompliant() {
3 char *src, *dst;
4 int left;
5
6 while (*src && left) {
7 *dst++=*src++;
8 // Compliant: Used equality operator.
9 if (left == 0) {
10 die("badlen");
11 }
12 left--;
13 }
14}