Jonas - 4 months ago 43

C++ Question

I'd like to multiply two

`unsigned integers`

`unsigned long long`

`unsigned long long M;`

unsigned int X;

unsigned int Y;

X = 999999;

Y = 9990;

M = X * Y;

`M`

`9989990010`

`1400055418`

I've been troubled with this for a week now, and I think I reached the point where I want to cry!

Answer

You need to cast the `X`

and `Y`

to `long long`

.

```
M = (unsigned long long)X * Y;
```

Enough to cast one of them the result will be based on the larger type.

Otherwise the result will be `int`

, hence the overflow. It will be casted to `long long`

on assignment, but that would be too late:-)