Search code examples
c++typecasting-operator

Why explicit typecasting is required here?


Why we explicitly need to typecast int to long long in multiplication?

t=(long long)n*(long long)n gives correct answer but t=n*n gives wrong answer:

#include <iostream>
using namespace std;

int main() {
int n=100000;
long long int t;
t=(long long)n*(long long)n;
//t=n*n  (This gives wrong answer)
printf("%lld",t);
return 0;
}

t=(long long)n*(long long)n gives 10000000000 where as t=n*n gives 1410065408 Why is it so?


Solution

  • Because n is an int type, n * n is an int type too. There's no "dynamic widening" in C++.

    Writing 1LL * n * n forces implicit conversions of the ns to long long types.

    Finally, note that even 100000 can be too big for an int - std::numeric_limits<int>::max() can be as small as 32767. If you want your code to be portable you need to write long n = 100000; and the expression for t as given.