Reputation: 35
Why when you do this:
int a = 1000000 , b = 1000000;
long long product = a * b;
cout<<product;
It gives some random trash value?Why do both a and b need to be long long in order to calculate it?
Upvotes: 2
Views: 808
Reputation: 15511
You are observing the effects of undefined behavior. This:
a * b
is an (arithmetic) expression of type int
, as both operands a
and b
are of type int
. Trying to store the value of 1000000000000 into an int
results in the so-called signed integer overflow which is undefined behavior.
Either cast one of the operands to long long
, thus causing the entire expression to become long long
, which is sufficiently large to accept the value of 1000000000000:
#include <iostream>
int main()
{
int a = 1000000, b = 1000000;
auto product = static_cast<long long>(a) * b;
std::cout << product;
}
Or define one of the operands as long long
:
#include <iostream>
int main()
{
long long a = 1000000;
int b = 1000000;
auto product = a * b;
std::cout << product;
}
Optionally, use unsigned long
instead.
Upvotes: 6
Reputation: 4349
This will work fine. When you do multiplication of int
and int
if it gets out of limit then to put it in a long long variable you multiply the result with 1ll
or 1LL
. When you multiply the result with 1ll
the result is converted to long long during calculation of product itself.
int a = 1000000 , b = 1000000;
long long product = 1ll * a * b;
cout << product;
Upvotes: 1