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

前端 未结 5 2033
别那么骄傲
别那么骄傲 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:26

    Another common solution is to typecast one of the constants to the larger, result type prior to operating on it. I prefer this method, since not everyone remembers all the possible suffixes. Including myself.

    In this case, I'd use:

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

    The sad part is that this is one thing assembly language—yes, assembly language—gets right that C, C++, and many other languages do not: The result of multiplying an M-bit integer by an N-bit integer is a (M+N)-bit integer, not a (max(M, N))-bit integer.

    EDIT: Mark makes an interesting point: the compiler does not "look ahead" to where the result is stored in order to infer a result type. Thus, C++ demands that the result of any sub-expression, by itself, be deterministic. In other words, the exact type of 100 * 30000000 can always be determined without looking at any other piece of code.

提交回复
热议问题