user8469759
user8469759

Reputation: 2732

Widening and narrowing rules in C/C++

I was trying to read through the C/C++ standard for this but I can't find the answer.

Say you have the following snippet:

int8_t m;
int64_t n;

And that at some point you perform m + n, the addition itself is a binary operator and I think the most likely think that happen in such a case is:

  1. Wide m to the same size of n, call the widening result m_prime
  2. Perform m_prime + n
  3. Return a result of type int64_t

I was trying to understand however if instead of performing m+n I had performed n+m the result would change (because maybe there could be a narrowing operations instead of a widening).

I cannot find the part of the standard that clarify this point (which I understand it could sound trivial).

Can anyone point me where I can find this in the standard? or what happens in general in situations like the one I exposed?

Personally I've been looking at the section "Additive operators" but it doesn't seem to me to explain what happens, pointer arithmetic is covered a bit, but there's no reference to some casting rule implicitly applied.

You can assume I'm talking about C++11, but any other standard I guess would apply the same rules.

Upvotes: 3

Views: 691

Answers (1)

Allison Lock
Allison Lock

Reputation: 2393

See Clause 5 Expressions [expr]. Point 10 starts

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

The sub-points that follow say things like "If either operand is...", "...the other shall...", "If both operands ..." etc.

For your specific example, see 10.5.2

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

Upvotes: 2

Related Questions