Does the order of multiplication of variables of different data types mean different results?

Suppose I have 3 variables: a long, a intand a short.

long  l; 
int   i;
short s;
long  lsum;

If this is pure mathematics, since multiplication has a commutative property, the order of these variables does not matter.

 l * i * s = i * s * l = s * i * l.

Let be the lsumcontainer for multiplying these three variables.

In C, would there be a case where a particular order of these variables produces a different result?

If there is a case where order matters, not necessarily from this example, what would it be?

+4
source share
2 answers

Order matters because of whole promotions.

int, int (, char short). (, long), .

6.3.1 C:

2 , int unsigned int:

  • ( int unsigned int), int unsigned int.

  • _Bool, int, signed int unsigned int.

int ( , ), int; unsigned int. . .

6.3.1.8:

, .

, unsigned integer, .

, , , , .

, , .

.

( sizeof(int) 4 sizeof(long) 8):

int i;
short s;
long l, result;

i = 0x10000000;
s = 0x10;
l = 0x10000000;

result = s * i * l;
printf("s * i * l=%lx\n", result);
result = l * i * s;
printf("l * i * s=%lx\n", result);

:

s * i * l=0
l * i * s=1000000000000000

s * i. s int, int . undefined. long l, long.

l * i. i long, long . s, long. , .

long, . , , .

+4

, . " " " " http://www.cplusplus.com/articles/DE18T05o/

unsigned a = INT_MAX;
unsigned b = INT_MAX;
unsigned long c = 255;

unsigned long r1 = a * b * c;
unsigned long r2 = c * a * b;

r1 = 255 r2 = 13835056960065503487

r1 , (a * b) , int, , , .

+3

Source: https://habr.com/ru/post/1677485/


All Articles