long long vs int multiplication

后端 未结 4 1538
轮回少年
轮回少年 2020-12-10 06:41

Given the following snippet:

#include 

typedef signed long long int64;
typedef signed int int32;
typedef signed char int8;

int main()
{
             


        
4条回答
  •  攒了一身酷
    2020-12-10 07:43

    The C99 standard does specify that binary operators such as * do not operate on integer types smaller than int. Expressions of these types are promoted to int before the operator is applied. See 6.3.1.4 paragraph 2 and the numerous occurrences of the words "integer promotion". But this is somewhat orthogonal to the assembly instructions generated by the compiler, which operate on ints because this is faster even when the compiler would be allowed to computed a shorter result (because the result is immediately stored in an l-value of a short type, for instance).

    Regarding int64 f = d * e; where d and e are of type int, the multiplication is done as an int in accordance with the same promotion rules. The overflow is technically undefined behavior, you are getting two-s-complement result here, but you could get anything according to the standard.

    Note: the promotion rules distinguish signed and unsigned types when promoting. The rule is to promote smaller types to int unless int cannot represent all values of the type, in which case unsigned int is used.

提交回复
热议问题