why overflow happens on calculation depending on the data type when the type where the value is being assigned can hold it

前端 未结 5 2030
别那么骄傲
别那么骄傲 2021-01-28 02:10

Earlier I came up with something, which I solved, but it got me later let\'s take a look at a similar example of what I was on:

int b = 35000000; //35million
int         


        
5条回答
  •  醉话见心
    2021-01-28 02:21

    Let me explain what is occuring here.
    On:

    int b= 35000000;
    unsigned long n = ( 100 * 30000000 ) / b;
    

    The value is incorrect because overflow happens at ( 100 * 30000000 ) But on:

    unsigned long b= 35000000;
    unsigned long n = ( 100 * 30000000 ) / b;
    

    The value is correct, so what is happening?

    In the first example b is a int, as said by Tony, an overflow happens because the register where the temporary value of ( 100 * 30000000 )will be assigned is able to hold 32bit signed integers, that happens because 100 is an int and 30000000 is also an int AND because b is also an int, the register in this case are smart, when ALL values on the right side are int it assumes the values also have to be an int but when a mighty unsigned long comes to the party, it knows that dividing an int by an unsigned long, / b is wrong, so it stores the value of ( 100 * 30000000 ) to an unsigned long.

提交回复
热议问题