Main Content

CWE Rule 482

Comparing instead of Assigning

Since R2023a

Description

Rule Description

The code uses an operator for comparison when the intention was to perform an assignment.

Polyspace Implementation

The rule checker checks for Invalid use of == (equality) operator.

Examples

expand all

Issue

This issue 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:

Example — Equality Evaluation in for-Loop
void populate_array(void)
{
    int i = 0;
    int j = 0;
    int array[4];

    for (j == 5; j < 9; j++)  //Noncompliant
    {
        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++;
    }
}

Check Information

Category: Others

Version History

Introduced in R2023a