Main Content

Write without a further read

Variable never read after assignment

Description

This defect 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.

Examples

expand all

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

    level = 4 * getsensor();            
    /* 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.

Result Information

Group: Data flow
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: USELESS_WRITE
Impact: Low

Version History

Introduced in R2013b