MISRA Discussion Forums

Full Version: Underlying type of sum of constants
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Consider:

namespace {
typedef unsigned short ui16;
const ui16 x = 1U;
const ui16 y = 2U;
const ui16 z = x + y;
}

Page 55 of MISRA C++ states:

"The underlying type of an integer constant expression is therefore defined as follows: 1. If the actual type of the expression is signed integral, the underlying type is defined as the smallest signed integer type that is capable of representing its value."

* The actual type of x + y is int
* The value of x + y is three
* The smallest signed type capable of representing three is signed char
* The underlying type of x + y is signed char

This also seems to match the behavior on page 60:

"The underlying type for a constant expression “e” with a value “v” will have the same signedness as “e”, and a magnitude given by the underlying type of a single integer-literal with the same value as “v”." (referring to page 58 "The underlying type of an integral literal is the smallest fundamental type of the appropriate sign required to store its value.")

where:

* "e" is x + y
* The actual type of "e" is int (determining signedness)
* "v" is three
* The underlying type of an integer literal with the value three is signed char (determining magnitude)
* The underlying type of x + y is signed char

Is this interpretation correct?
The bottom of the question is whether the last line in the example shown violates rule 5-0-4 although both operands appear to be unsigned:

Code:
namespace {
typedef unsigned short ui16;
const ui16 x = 1U;
const ui16 y = 2U;
const ui16 z = x + y;// violation of rule 5-0-4 without explicitly casting the result (static_cast(x + y))???
}

It would decrease readability as stated on page 55, so i think clarification is important for both developers and tool suppliers.
On page 55 an integer constant expression is said to be made up only of literals.
But the literals (1U and 2U) have already been turned into constants with a different type, so that has to make a difference, right?
Thanks.
We agree that there is an ambiguity in the wording as to what is meant by 'actual type'. It was not our intention that the example should be reported as a violation of 5-0-4 or anything else.

There is also an omission in the definition on page 55, it should say that an integer constant expression is made up only of literals or integer constants

This will be addressed in the next version