Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

c - long long vs int multiplication

Given the following snippet:

#include <stdio.h>

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

int main()
{
    printf("%i
", sizeof(int8));
    printf("%i
", sizeof(int32));
    printf("%i
", sizeof(int64));

    int8 a = 100;
    int8 b = 100;
    int32 c = a * b;
    printf("%i
", c);

    int32 d = 1000000000;
    int32 e = 1000000000;
    int64 f = d * e;
    printf("%I64d
", f);
}

The output with MinGW GCC 3.4.5 is (-O0):

1
4
8
10000
-1486618624

The first multiplication is casted to an int32 internally (according to the assembler output). The second multiplication is not casted. I'm not sure if the results differ because the program was running on a IA32, or because it is defined somewhere in the C standard. Nevertheless I'm interested if this exact behavior is defined somewhere (ISO/IEC 9899?), because I like to better understand why and when I've to cast manually (I've problems porting a program from a different architecture).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...