clogicexponentiation

Why is the exponent operator not giving the expected result?


Here is the code

#include <stdio.h>

int main()
{
 int a;
 printf("%d\n",(3^6));
 printf("%d",(a^a));
 return 0;
}

I am getting the below output on executing the above code.

5
0

Shouldn't the output be 729? 3 to the power of 6 is 729. I could not understand the logic of why it is returning 5?


Solution

  • The ^ operator is bitwise xor. To understand why 3^6 is 5 let's look at binary representations of those values:

    3 = 0011
    6 = 0110
    

    and so

    3^6 = 0101 = 5
    

    You did not initialise a, which means that a^a is undefined behaviour.


    For exponentiation you need to use pow().