Jonas Jonas - 1 month ago 5x
C++ Question

unsigned long long arithmetics

I'd like to multiply two

unsigned integers
but I want the result to be in an
unsigned long long

unsigned long long M;
unsigned int X;
unsigned int Y;

X = 999999;
Y = 9990;
M = X * Y;

should be
but for some reason it keeps being

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


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:-)