In other words does this work as expected?
int32 i = INT_MAX-1;
int64 j = i * i;
or do I need to cast the i to 64 bit first?
In other words does this work as expected?
int32 i = INT_MAX-1;
int64 j = i * i;
or do I need to cast the i to 64 bit first?
You need to cast at least one of the operands to the multiply. At the point the multiply is being done, the system doesn't know you're planning to assign to an int64.
(Unless int64 is actually the native int type for your particular system, which seems unlikely)
It depends on what int32 and int64 are.
In brief, all integers are promoted to at least 'int' size (which may be 64 bits) before any arithmetic operations, and to the size of the larger operand for binary operators if this is of greater rank than an int.
How the result of an expression is used (whether or not it is stored to a wider type) has no bearing on the promotions of the constituent parts of the expression.
Given two numbers a,b and each number uses len_a and len_b bits.
Your output datatype needs at least: len_a and len_b bits.
In your above code, you have two 31 bit numbers ( because INT_MAX - 1 = 0x7FFFFFFE uses 31 bits ) and you will need to typecast one of them to int64_t because it will do a 32 bit multiply and overflow before it casts to int64_t.
The number of bits needed for fixed point multiplication:
len_output = howManyBits( a * b )
= len_a + len_b
A quick example to show the above rule in action:
a = 7
len_a = 3
b = 7
len_b = 3
c = a * b
= 49 ( decimal )
= 0x31 ( hex )
len_c = howManyBits( 0x31 )
= 6
You can write a function to count bits. Or if you just want a quick sanity check to confirm this use something like Windows Calc that will convert the number into binary form and count the bits used.
The basic answer is no it will not do what you want.
But it does do what is expected.
Two things to note about mathematical operations:
If the compiler notes a mismatch between the operands it will convert one of the operands so that both match (see http://stackoverflow.com/questions/245740/which-variables-should-i-typecast-when-doing-math-operations-in-c-c/245986#245986). Note: This is done in isolation to what happens to the result.
See: 14. Mixed use of simple integer types and memsize types. http://www.viva64.com/art-1-2-599168895.html