Paolo Caponeri
Paolo Caponeri

Reputation: 127

Subtracting an int from a long long int

  1. Can I subtract an int variable from a long long int variable?

  2. In case I can't: I need to store a bigger number than a number that can stored in a int, and I don't want to use a double or float because I need integers, what can I do? I don't want to use all long long int. Is there a way to cast the int into a long long int so that I can make the subtraction?

Upvotes: 1

Views: 6208

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

Yes you can. The int will be converted by the usual arithmetic conversions to a long long int for the sake of the subtraction, so that both operands have the same integer conversion rank, and the result will also be a long long int.

This is covered by §5/9:

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:

[...]
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.
[...]

The rank of long long int is greater than the rank of int.

Upvotes: 6

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

  1. Yes; the result is a long long (until you cast it to something else; in fact, it is a long long but you might convert the result to a different type).

  2. N/A.

Upvotes: 1

NPE
NPE

Reputation: 500357

Yes, you can subtract an int from a long long int. You won't need any explicit casts since the int will be widened automatically.

Upvotes: 2

Related Questions