Main Content

AUTOSAR C++14 Rule A5-1-1

Literal values shall not be used apart from type initialization, otherwise symbolic names shall be used instead

Description

Rule Definition

Literal values shall not be used apart from type initialization, otherwise symbolic names shall be used instead.

Rationale

Improve the readability and maintainability of code by using symbolic names. Literal constants do not clearly indicate what the constant represents

Polyspace Implementation

Polyspace® flags the use of literal values other than those with the data type char in expressions and case clauses of a switch statement.

Polyspace does not flag the use of literal values in logging mechanisms.

Polyspace does not flag the use of literal values '0' and '1' in expressions, as they are often part of the logic of the code. For instance, '0' represents a NULL pointer.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

double foo(void){
	constexpr int speedLimit = 65;
	constexpr double coeff = 0.2;
	int flag{0};
	int negOne{-1};
	//... 
	return (flag)?speedLimit*coeff*negOne + 35 //Noncompliant
			: speedLimit*coeff*negOne - 35; //Noncompliant
}

double bar(void){
	constexpr int speedLimit = 65;
	constexpr double coeff = 0.2;
	int flag{0};
	int negOne{-1};
	int addedValue = 35;
	return (flag)?speedLimit*coeff*negOne + addedValue //Compliant
			: speedLimit*coeff*negOne - addedValue; //Compliant
}

In this example, Polyspace flags the use of literal values in the return expression of foo. In bar, the return expression uses symbolic names, which makes code more readable. The use of literals to initiate objects does not violate this rule.

Check Information

Group: Expressions
Category: Required, Partially automated

Version History

Introduced in R2019a

expand all