Main Content

Invalid use of == operator

Equality operation in assignment statement

Description

This defect occurs when you use an equality operator instead of an assignment operator in a simple statement.

Risk

The use of == operator instead of an = operator can silently produce incorrect results. If you intended to assign a value to a variable, the assignment does not occur. The variable retains its previous value or if not initialized previously, stays uninitialized.

Fix

Use the = (assignment) operator instead of the == (equality) operator.

The check appears on chained assignment and equality operators such as:

compFlag = val1 == val2;
For better readability of your code, place the equality check in parenthesis.
compFlag = (val1 == val2);

If the use of == operator is intended, add comments to your result or code to avoid another review. See:

Examples

expand all

void populate_array(void)
{
    int i = 0;
    int j = 0;
    int array[4];

    for (j == 5; j < 9; j++) {
        array[i] = j;
        i++;
    }
}

Inside the for-loop, the statement j == 5 tests whether j is equal to 5 instead of setting j to 5. The for-loop iterates from 0 to 8 because j starts with a value of 0, not 5. A by-product of the invalid equality operator is an out-of-bounds array access in the next line.

Correction — Change to Assignment Operator

One possible correction is to change the == operator to a single equal sign (=). Changing the == sign resolves both defects because the for-loop iterates the intended number of times.

void populate_array(void)
{
    int i = 0;
    int j = 0;
    int array[4];

    for (j = 5; j < 9; j++) {
        array[i] = j;
        i++;
    }
}

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: BAD_EQUAL_EQUAL_USE
Impact: High

Version History

Introduced in R2013b