Assign a small number to unsigned long long data-type without casting

I became a little bit confuse about assigning a small number to a big data-type variable, for example in my code (checkout online) :

#include <iostream>

int main()
{
  unsigned long long num = 5000000000;
  unsigned long long num2 = static_cast<unsigned long long>(5000000) * static_cast<unsigned long long>(1000);
  unsigned long long num3 = 5000000 * 1000UL;       // Casting 1000 to long data-type
  unsigned long long num4 = 5000000 * 1000;
  std::cout << num << std::endl << num2 << std::endl << num3 << std::endl << num4;
  
  return 0;
}

The output is

5000000000
5000000000
5000000000
705032704

I know about literal casting and static_cast feature in c++ and also about the compiler behavior that always casting with the biggest data-type in a mathematical statement.

But the problem is here that why the result of statement unsigned long long num4 = 5000000 * 1000; is the number 705032704 and not 5000000000? BTW i know when i cast it like 5000000 * 1000UL; it gives me 5000000000 (because it cast to largest data-type).

Regards!

Upvotes: 0

Views: 885

Answers (1)

Mark Roberts
Mark Roberts

Reputation: 138

Your line unsigned long long num4 = 5000000 * 1000; consists of three independent parts which are evaluated separately.

  • The right-hand-side is evaluated as int because all the operands are int. The result is not what you expect because of an integer overflow.

  • The left-hand-side makes space for an unsigned long long.

  • The assignment copies the (unexpected) result from the right-hand-side into the space allocated for the variable.

Upvotes: 3

Related Questions