Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence while type casting in C

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?

like image 854
RuD Avatar asked Jan 22 '15 11:01

RuD


People also ask

What is the precedence of operators in C?

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.

Which operator is used for type casting?

Cast operator: () A type cast provides a method for explicit conversion of the type of an object in a specific situation.

Which operators in C have the highest precedence?

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.

Which operator type has the highest precedence?

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-- .


2 Answers

(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.

like image 109
masoud Avatar answered Oct 11 '22 10:10

masoud


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;
like image 39
sramij Avatar answered Oct 11 '22 12:10

sramij