## Underlying type of sum of constants

Moderators: david ward, misra cpp

abgs
Posts: 12
Joined: Wed Sep 06, 2017 4:25 pm
Company: Gimpel Software

### Underlying type of sum of constants

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?

dg1980
Posts: 109
Joined: Wed Apr 27, 2016 2:33 pm
Company: Elektrobit Automotive GmbH

### Re: Underlying type of sum of constants

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: Select all

``````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<ui16>(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.

misra cpp
Posts: 151
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

### Re: Underlying type of sum of constants

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
Posted by and on behalf of
the MISRA C++ Working Group