Reputation: 225
In the following expression, what conversion happens?
long long a;
long long b;
double c;
b=a*c;
suppose the long long
type is 8-byte.
If a
and b
are both int
, then in the expression b = a * c
, a
will be converted to double
and does multiplication with c
, and the result will be converted to int
and assigned to b
.
Is my assumption correct?
Upvotes: 1
Views: 102
Reputation: 310980
According to the C Standard (6.3.1.8 Usual arithmetic conversions)
1 Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result....This pattern is called the usual arithmetic conversions:
...
Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double
And (6.5.16 Assignment operators)
- The type of an assignment expression is the type the left operand would have after lvalue conversion.
and (6.5.16.1 Simple assignment)
2 Insimple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
Thus in this statement
b = a * c;
at first object a
is converted to type double
and the evaluated right operand has type double
. After that the value of the right operand is converted to the type of the assignment expression that has the type of the left operand that is the result of a * c
is converted to long long int
.
Take into account that even if c
is equal to 1 expression a * c
is not necessary equal to a * 1
due to the conversions
Consider the following program
#include <stdio.h>
#include <limits.h>
int main( void )
{
long long a = LLONG_MAX;
long long b;
double c = 1;
printf( "a = %lld\n", a );
printf( "c = %lf\n", c );
b = a * c;
printf( "b = %lld\n", b );
}
The program output might look like
a = 9223372036854775807
c = 1.000000
b = -9223372036854775808
Upvotes: 0
Reputation: 30489
b=a*c;
is equivalent to:
b=(long long) ( (double)a * c );
So there are two conversions involved, first from long long
to double
and second from double
result to long long
For more details check this page from Joachim Pileborg's comment
Upvotes: 2
Reputation: 134326
As per C11
standard, chapter §6.3.1.8, Usual arithmetic conversions
....Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is
double
.
So, your statement is essentially,
b= (long long)( (double)a * c );
that is, for the *
operand, c
is double
, so value of a
is converted to a double
value, the multiplication is performed, the result is of type double
and finally, that value is being converted to long long
, when assigned to b
, as per the type of b
itself.
Upvotes: 1