As others have pointed out, the problem is that ^
is the bitwise xor operator. C has no exponentiation operator.
You're being advised to use the pow()
function to compute the square of an int
value.
That's likely to work (if you're careful), but it's not the best approach. The pow
function takes two double
arguments and returns a double
result. (There are powf
and powl
functions that operator on float
and long double
, respectively.) That means that pow
has to be able to handle arbitrary floating-point exponents; for example, pow(2.0, 1.0/3.0)
will give you an approximation of the cube root of two.
Like many floating-point operations, pow
is subject to the possibility of rounding errors. It's possible that pow(3.0, 2.0)
will yield a result that's just slightly less than 9.0
; converting that to int
will give you 8
rather than 9
. And even if you manage to avoid that problem, converting from integer to floating-point, performing an expensive operation, and then converting back to integer is massive overkill. (The implementation might optimize calls to pow
with integer exponents, but I wouldn't count on that.)
It's been said (with slight exaggeration) that premature optimization is the root of all evil, and the time spent doing the extra computations is not likely to be noticeable. But in this case there's a way to do what you want that's both simpler and more efficient. Rather than
int nSquared = n^2;
which is incorrect, or
int nSquared = pow(n, 2);
which is inefficient and possibly unreliable, just write:
int nSquared = n * n;