Main Content

Unused variable

Variable defined or declared but not read or written

Since R2024a

Description

This defect occurs when a nonstatic local, static local, or static global variable is declared or defined but not read in any source files within the scope of the Polyspace® analysis. Polyspace does not report this defect for variables that are members of a class, struct, or union.

Risk

An unused variable can indicate possible logic errors or architectural errors in your code. If an unused variable is expensive to construct or destroy, then it can make the code unnecessarily expensive.

Fix

To fix this defect, review your code and determine why variables are unused. Remove unnecessary variables and revise your code so that remaining variables are used.

Examples

expand all

In this C++ example, the string reversed is not used by the function isPalindrome. Polyspace reports a defect.

#include <string>

bool isPalindrome(const std::string& str) {
    std::string reversed;
    int length = str.length();
    for (int i = 0; i < length / 2; i++) {
        if (str[i] != str[length - i - 1]) {
            return false;
        }
    }
    return true;
}
Correction — Remove Unused Variable

To fix this defect, remove the unused variable.

#include <string>

bool isPalindrome(const std::string& str) {
    int length = str.length();
    for (int i = 0; i < length / 2; i++) {
        if (str[i] != str[length - i - 1]) {
            return false;
        }
    }
    return true;
}

Result Information

Group: Good Practice
Language: C | C++
Default: Off
Command-Line Syntax: UNUSED_VARIABLE
Impact: Low

Version History

Introduced in R2024a

expand all