The following piece of code gives the correct result for the multiplication
int var0 = 245895;
int var1 = 478565
long long val = 0;
val = (long long) var0 * var1;
but this piece gives the incorrect result:
int var0 = 245895;
int var1 = 478565
long long val = 0;
val = (long long) (var0 * var1);
Could anybody help me with why?
Operator precedence determines which operation is performed first in an expression with more than one operators with different precedence. Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left.
Cast operator: () A type cast provides a method for explicit conversion of the type of an object in a specific situation.
Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
(long long) var0 * var1
~~~~~~~~~~~~~~~~
1
~~~~~~~~~~~~~~~~~~~~~~~
2
In the above code, first var0
casts to long long
, after that, the result of multiplication will be calculated as long long
with no overflow. In fact compiler promotes the type of var1
from int
to long long
implicitly.
(long long) (var0 * var1)
~~~~~~~~~~~~~
1
~~~~~~~~~~~~~~~~~~~~~~~~~
2
In the second code, first multiplication occurs and the result doesn't fit in a long
type, so the cast after that doesn’t help anymore. It casts the number that is overflow-ed before.
Therefore, the first one is better than second one to avoid overflows.
It's all a matter of how the mid calculation result is stored:
val = (long long) (var0 * var1);
is interpreted as:
int midResult = (int)var0 * (int)var1;
val = (long long)midResult;
While, val = (long long) var0 * var1
is interpreted as:
long long midResult = (long long) var0 * (long long)var1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With