tags:

views:

53

answers:

1

I'm confused about the rules concerning this matter [a good URL might save time in answering]. I notice that a lot of the time conversion implicitly works but other times it's required.

e.g. I had expected it to work:

long long a;
int b;
[..]
a = b * 1000;

but it turns out, 'a' overflows and it's required to

a = (long long) b * 1000;

That was peculiar since 'a' being the 'big one' I had expected it would bother.

Anyway, apart from that example, do you know a comprehensive source of information on the matter? No 'most of the time is ok', that gets me paranoid.

EDIT: Is it only a matter of 'the second part does the calculation first and there it overflows, follow that rule closely'?

EDIT2: If there is a calculation such as

long long a;
int b;
short c;
[..]
c = b + a * 3;

, would doing

c = b + (int) a * 3; 

ensure proper conversion?

or would it need

c = (short) b + (int) a * 3; 

or, would it be enough to

c = (short) b + a * 3; 
+6  A: 

Type conversions works step by step. Your expression can be viewed as

a = (b * 1000);

in the b * 1000, the compiler (let's pretend it's stupid) doesn't know you are going to store it into a long long. Since both b and 1000 are ints, the result will be an int also. How big a is doesn't matter here.

You could avoid the cast by making 1000 a long long.

a = b * 1000LL;

Edit: For your edit 2:

  • a is a long long, b is an int, 3 is an int.
  • Therefore, a * 3 is a long long
  • Therefore, b + a*3 is a long long
  • But a cast is not needed in c = b+a*3, as a arithmetic operands are implicitly convertible to each other.
KennyTM
Well, it does know that you are going to store it in a long long, but it thinks that you want int arithmetic to calculate the result that will be stored there.
anon
So by making 1000 an LL is it like saying 'hey, one of those two numbers in the calculation is an LL, don't do anything stupid and overflow into an int, do the calculation as a LL.'? Is it that simple?
Lela Dax
@Lela: Yes. [ ](http://.com)
KennyTM