Here is a small Program to print powers of 2 till 8. But it is not quitting after 8. Please explain the reason.
#include <stdio.h>
#include <unistd.h>
int main(void)
{
unsigned int i=1;
while(1) {
i = i<<1;
printf("i = %d\n",i);
if(i==(2^8))
break;
sleep(1);
}
printf("Exited While loop.. \n");
return 0;
}
The Loop is not Exiting when i = 2^8. My output is something like this:
i = 2
i = 4
i = 8
i = 16
i = 32
i = 64
i = 128
i = 256
i = 512 (Should have Exited here. But the program is continuing. Why?)
i = 1024
i = 2048
i = 4096....
EDIT :
Thanks for answering that ^ is an XOR operator. But now the below code is behaving strange. Please Explain.
#include <stdio.h>
int main(void)
{
if((2)^8 == 1<<8) {
printf("True.. \n");
} else {
printf("False..!!");
}
return 0;
}
The above function program prints true.
In C, the ^ operator means XOR (bitwise exclusive or).
To get 2 to the power of 8, you need to either use a loop (res *=2 in a loop), or round the pow function in math.h (note that the math.h function returns float – and therefore won’t be equal to the integer).
The simplest method is the bitwise shift, of course.
About the edit section:
Welcome to the wonderful world of operator precedence.
What happens is that == has higher precedence than ^, and therefore the conditional evaluates to 2^0, which is 2, which is true.
To make it work, you need to add parentheses: