ElkeAusBerlin
ElkeAusBerlin

Reputation: 575

Arithmetic operation on int32 and int64 with parentheses

given this operation:

int64_t a_int64, b_int64 = WHATEVER1;
int32_t c_int32 = WHATEVER2;

a_int64 = b_int64 - (c_int32 * 1000000);

Is c_int32 promoted to int64_t before the multiply? I know all integers are promoted to at least 'int' size before any arithmetic operations, and to the size of the larger operand for binary operators if this is of greater rank than an int. But are operations inside parentheses' are handled separately from the (second) operation, the substraction?

Upvotes: 1

Views: 987

Answers (2)

ruakh
ruakh

Reputation: 183211

But are operations inside parentheses' are handled separately from the (second) operation, the substraction?

Yes; the promotions involved in evaluating c_int32 * 1000000 do not depend in any way on the context. Any necessary conversions due to that context happen on the result, afterward.

That said, c_int32 * 1000000 is only well-defined in cases where it doesn't overflow; and in such cases, it doesn't matter whether the 64-bit promotion happens before or after the multiplication. So a compiler could legitimately do it either way (e.g., if it sees some optimization opportunity).

Upvotes: 2

Cloud
Cloud

Reputation: 19333

From another good SO post on the topic:

C99, §6.4.4.1

The type of an integer constant is the first of the corresponding list in which its value can be represented.

Table 6

int
long int
long long int

So, the automatic promotion of c_int32 will depend on the size of the integer literal. In this case, on a 32-bit system, your integer literal will easily fit within an in32_t variable.

This is not a good way to do integer arithmetic. Make your code as explicit as possible, and leave nothing to chance.

a_int64 = b_int64 - ((int64_t)c_int32 * 1000000LL);

Upvotes: 2

Related Questions