c++ - Type casting when exceeding the limit -


i want multiply 2 int numbers and, in order prevent exceeding int limit (2147483647), result saved in long long variable. so, try piece of code:

int a, b; long long result = * b; 

and it doesn't work! if a=50000 , b=50000 result=-1794967296.

therefore, have apply type casting a , b:

int a, b; long long result = (long long)a * (long long)b; 

why necessary apply type casting in case?

note: don't want change data type of a , b, need keep them int.

since a , b int, product a*b int also. product big overflows , incorrect value.the cast needed product long long.

by way, don't need cast both operands. 1 enough:

long long result = * (long long)b; 

the other 1 promoted long long also. see this online demo.

by way, prefer c++-style cast on c-style cast:

long long result = * static_cast<long long>(b); 

hope helps.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -