Main Content

Redundant expression in sizeof operand

sizeof operand contains expression that is not evaluated

Since R2020a

Description

This defect occurs when a sizeof operand contains expressions whose evaluation does not affect the sizeof result. In place of the current expression in the sizeof operand, a data type, a variable or a simpler expression could have been used without any loss of functionality.

Risk

In situations flagged by this defect, the expression in the sizeof operand is needlessly complicated, reduces the code readability and adds to maintainability costs. The expression might also give a false impression about the result of the sizeof operand.

For instance, consider the expression:

sizeof(void (*[n])(int arr[U+V]))
The operand of sizeof is an array of n function pointers, each of type void () (int*). The additional U+V, which is not evaluated, makes the full expression needlessly complicated. The expression also gives the false impression that the function pointer argument being an array of size U+V matters for the sizeof result.

Fix

The first event in the defect traceback shows where the redundant subexpression of the sizeof operand begins.

Simplify or completely remove the redundant expression. When possible, use a data type as the sizeof operand. For instance, in the preceding example, a simpler equivalent sizeof operation is:

sizeof(void (*[n])(int*))

If you want the expression to be evaluated, perform the evaluation in a separate statement.

Examples

expand all

void func() {
    int size1, size2, size3;
    char x = 0;
    short y = 0;
    int z = 0, w = 0;
    
    size1 = sizeof(x + y);
    size2 = sizeof(x + z);
    size3 = sizeof(z + w);
}

In this example, the defect checker flags the second and third sizeof operation because the expressions in the sizeof operand can be simplified without changing the sizeof result.

The checker does not flag the first operation because the expression in the sizeof operand cannot be simplified further without affecting the sizeof result.

Correction – Simplify Expression in sizeof Operand

Simplify the expression in the sizeof operand. In the following corrections, the sizeof results are the same as with the preceding expressions.

void func() {
    int size1, size2, size3;
    char x = 0;
    short y = 0;
    int z = 0, w = 0;
    
    size1 = sizeof(x + y);
    size2 = sizeof(z);
    size3 = sizeof(z);
}

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: SIZEOF_USELESS_OP
Impact: Low

Version History

Introduced in R2020a