Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Squaring a number in C++ yields wrong value

Tags:

c++

If I do

 int n = 100000;
 long long x = n * n;

then x == 1410065408

1410065408 is 2^31, yet I expect x to be 64 bit

What is going on? I'm using VSC++ ( default VS c++ compiler )

like image 886
Christo S. Christov Avatar asked Jul 23 '16 17:07

Christo S. Christov


1 Answers

n*n is too big for an int because it is equal to 10^10. The (erroneous) result gets stored as a long long.

Try:

long long n = 100000;
long long x = n*n;

Here's an answer that references the standard that specifies that the operation long long x = (long long)n*n where n is an int will not cause data loss. Specifically,

If both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

Since the functional cast has the highest precedence here, it converts the left multiplicand to a long long. The right multiplicand of type int gets converted to a long long according to the standard. No loss occurs.

like image 120
Jossie Calderon Avatar answered Sep 28 '22 12:09

Jossie Calderon