Why is my power operator (^) not working?

#include <stdio.h>

void main(void)
{
    int a;
    int result;
    int sum = 0;
    printf("Enter a number: ");
    scanf("%d", &a);
    for( int i = 1; i <= 4; i++ )
    {
        result = a ^ i;

        sum += result;
    }
    printf("%d\n", sum);
}

Why is ^ not working as the power operator?


Well, first off, the ^ operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.

Now, regarding your problem with using the pow() function, some googling shows that casting one of the arguments to double helps:

result = (int) pow((double) a,i);

Note that I also cast the result to int as all pow() overloads return double, not int. I don't have a MS compiler available so I couldn't check the code above, though.

Since C99, there are also float and long double functions called powf and powl respectively, if that is of any help.


In C ^ is the bitwise XOR:

0101 ^ 1100 = 1001 // in binary

There's no operator for power, you'll need to use pow function from math.h (or some other similar function):

result = pow( a, i );