Computing with a variable outside its bounds in C

If I do a calculation with a variable where the intermediate part of the calculation goes higher than the boundaries of this type of variable, is there any danger for some platforms?

This is an example of what I am asking:

int a, b;
a=30000;
b=(a*32000)/32767;

I compiled this and it gives the correct answer 29297 (well, within the limits of a truncated error, anyway). But what bothers me is that 30,000 * 32,000 = 960,000,000, which is a 30-bit number and therefore cannot be stored in a 16-bit int. The end result lies well within int, but I expected that any working part of the memory would be the same size as the largest source variables, so an overflow error occurred.

This is just a small example to show my problem. I try to avoid the use of floating points, making the fraction equal to the fraction of the maximum amount that can be stored in this variable (in this case, a signed integer, therefore 32767 on the positive side), because the built-in system that I use, I believe, is not has an FPU.

So, how do most processors handle calculations from the boundaries of the source and target variables?

+3
source share
6 answers

16- / () , . , ( ) , C ( ) ( a b , ).

. , muldiv , ( ), , , , C, .

- , , . , , , ...

+3

, , * - , 8- * 8 16- (-) 8- , 32- * 32- 64- (-) 32- . ( , , )

, , * .

+2

AFAIK "undefined". , . . , , .

, , .

- , C. .

, , , - .

short a= 30000;
int temp= a;
int temp2= (a*32000)/32767;
// here you can check for errors; if temp2 > 32767, you have overflow.
short b= a;
0

- undefined.

, , , (a) 2 , , (b) C.

, 16- int 0 ( , , 16- 16- int). , , ..

, 16- short 32- int, , , "" 29297, (a*32000) int, short. "", , . , , , .

0

, 16- ? int 32 . , , , , - .

, , -, . , 16- . , , ? , - :

int a, b;
a=30000;
//b=(a*32000)/32767 ~= a * (32000/32768) = a *(125/128)
b = (a / 128) * 125 // if a=30000, b = 29250 - about 0.16% error

- . 16- int 32- , - :

int a, b;
a=30000;
b=((long)a*32000L)/32767L;

, , . , .

0

- . , , , . C, , . AVR, 8- , , int 16 , , , - , int unsigned int, , . (, int, long, long long) , . , sizeof() . / , , uint32_t int64_t .

0
source

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


All Articles