Main Content

Useless preprocessor conditional directive

Preprocessor conditional directive is always true or always false

Since R2022a

Description

This defect occurs when a preprocessor conditional directive always evaluates to the same logical value. For instance, you might be testing for the condition in a previous conditional directive. Consider this code:

long sensorFlag;
#if cond1
  sensorFlag = 0x0001;

#elif cond2
  sensorFlag = 0x00AA;

#else
    #if cond1 //Always false
        sensorFlag = 0xFF00;
    #endif
#endif
In the #else block, the conditional directive #if cond1 is executed only when cond1 is false. This directive is always false. Polyspace® flags conditional directive that always evaluates to the same logical value.

Risk

If a conditional directive is always true or always false, it might indicate an inadvertent error. For instance, the conditional directive might be unexpectedly impacted by a change elsewhere in your code. Alternatively, your conditional directive design might contain unexpected errors. In the preceding code, the statement #if cond1 might be a typographical error. The developer intent might have been to use #if cond3.

Fix

To fix this defect, remove the flagged conditional directive. If the useless conditional is unexpected, review and refactor your code.

Examples

expand all

#define THE_ANSWER 42

#if defined(UNIVERSE)
	#define STARS 1
	#define MILKY_WAY 1
	#if defined(UNIVERSE) // Defect
		#define SUN 1
	#endif
#else
	#define STARS 0
	#define MILKY_WAY 0

	#if defined(UNIVERSE) // Defect
		#define SUN 0
	#endif
#endif

In this example, Polyspace flags two useless preprocessor conditional directives.

  • The conditional directive if defined(UNIVERSE) on line six is placed inside the conditional block that starts with the same conditional. The flagged conditional is reached only when it is always true. Because this conditional is always true, you can remove it without changing code behavior. Polyspace flags the useless preprocessor directive.

  • The conditional directive if defined(UNIVERSE) on line 13 is reached only when the same conditional evaluates to false. Because this conditional is always false, you can remove it without changing code behavior. Polyspace flags the useless preprocessor directive.

Correction — Remove Useless Preprocessor Conditional Directives

To fix this defect, remove the useless conditional directives. Alternatively, redesign your code. For instance, when the token UNIVERSE is undefined, you might set the value of SUN to zero without performing another check on UNIVERSE.

#define THE_ANSWER 42

#if defined(UNIVERSE)
	#define STARS 1
	#define MILKY_WAY 1
	#define SUN 1
#else
	#define STARS 0
	#define MILKY_WAY 0
	#define SUN 0
#endif

Result Information

Group: Data flow
Language: C | C++
Default: Off
Command-Line Syntax: USELESS_PREPROC_CONDITION
Impact: Low

Version History

Introduced in R2022a