3

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?

4 Answers4

7

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().

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
4

The ^ operator in C isn't for exponents : it is the bitwise xor.

00000011 (3)
xor
00000110 (6)
=
00000101 (5)

Use pow() for exponents.

And you didn't initialize a, so be careful with that.

maxdefolsch
  • 179
  • 5
1

The operator ^ in C is not power - C has no builtin operator for that, only pow function:

double x = pow(3,5);

The operator ^ is bitwise XOR.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0
^ 

is a operator used for XORing. include #include<math.h> header file and use pow(3,6) to evaluate power and u'll get 729

jaimin
  • 563
  • 8
  • 25