In Keil C51, to quote the manual:
The sbit type defines a bit within a special function register (SFR)
So you are not declaring a variable X and reading it once before the loop, rather you are defining a reference to P3.3, and reading it's state on every iteration of the loop. That is to say that X is a reference to the hardware I/O pin register, not a variable.
Despite appearances sbit
is not a simple typedef
alias and the ^
is not a bitwise XOR operator. Rather it defines a reference to a bit addressable register. Assigning X
writes to the hardware register - the behaviour is then defined by the hardware in this case rather than the language. The ability to apparently change the value of X when it is externally pulled high, I am guessing is in the nature of the GPIO hardware rather than any strange behaviour of the !
operator. Check the hardware documentation for I/O pin behaviour, but I am guessing again that pulling it high makes the pin output-capable
To get the behaviour (I imagine) you expect you would code it thus:
sbit p = P3 ^ 3; // p is third bit of P3 register
...
int X = p ; // get p's current value
while (1) {
X = !X; // X equals not X ?!
if (X == 0)
printf("0");
else
printf("1");
}