Main Content

CWE Rule 563

Assignment to Variable without Use

Since R2023a

Description

Rule Description

The variable's value is assigned but never used, making it a dead store.

Polyspace Implementation

The rule checker checks for Write without a further read.

Examples

expand all

Issue

This issue occurs when a value assigned to a variable is never read.

For instance, you write a value to a variable and then write a second value before reading the previous value. The first write operation is redundant.

Risk

Redundant write operations often indicate programming errors. For instance, you forgot to read the variable between two successive write operations or unintentionally read a different variable.

Fix

Identify the reason why you write to the variable but do not read it later. Look for common programming errors such as accidentally reading a different variable with a similar name.

If you determine that the write operation is redundant, remove the operation.

Example — Write Without Further Read Error
void sensor_amplification(void)
{
    extern int getsensor(void);
    int level;

    level = 4 * getsensor();  //Noncompliant
    /* Defect: Useless write */
}

After the variable level gets assigned the value 4 * getsensor(), it is not read.

Correction — Use Value After Assignment

One possible correction is to use the variable level after the assignment.

#include <stdio.h>

void sensor_amplification(void)
{
    extern int getsensor(void);
    int level;

    level = 4 * getsensor(); 
    
    /* Fix: Use level after assignment */
    printf("The value is %d", level);
    
}

The variable level is printed, reading the new value.

Check Information

Category: Bad Coding Practices

Version History

Introduced in R2023a