Reputation: 73
#include<stdio.h>
int main()
{
int x=1,y=1;
for(;y&x<6;printf("%d %d\n",x,y++))
x++;
}
Here I expected an output like:
2 1
3 2
4 3
5 4
6 5
but I got an output
2 1
Upvotes: 2
Views: 437
Reputation: 564
I recommand
#include<stdio.h>
int main()
{
int x,y;
for(x = 1, y = 1; (y & x)<6;printf("%d %d\n",x,y++));
x++;
return 0;
}
because, as pointed by @coderredoc, >
has higher precedence than &
.
Upvotes: 0
Reputation: 163
Are you trying to check if both y and x are smaller than 6?
if so, instead of y&x<6
you should use (y<6)&&(x<6)
Upvotes: 1
Reputation: 30916
Because <
has higher precedence than &
from here.
So in the second iteration y=2
and x=1
. x<6
becomes true - results in 1
which when AND
ed with y
the result becomes 0
. So it stops. y<x&6
is equivalent to y&(x<6)
.
To explain you how AND
works :- (shown in 6 bits - but the logic holds same way for sizeof(int)*8
bits
).
000010
AND 000001
----------
000000
Upvotes: 1
Reputation: 71
#include<stdio.h>
int main()
{
int x=1,y=1;
for(;y<6&x<6;printf("%d%d_",x,y++))
x++;
}
try this
Upvotes: 0