Why this code wasn't written in a much simpler way?

You are right in that it appears the code you show is silly. Perhaps whatever machine this runs on can't do immediate operations to set bits on I/O ports, and that that's why something like SETB P2.2 isn't possible.

Still setting the CY bit to 1, then ORing anything into it is just plain silly. The same goes for setting the CY bit to 0, then ANDing something into it. Clearly the CY bit can be directly copied into a I/O pin bit, since the code does that. At most this should be 4 instructions, certainly not 6.


The code is almost certainly for a processor using the 8051 instruction set. On that processor, the code variation you give would have the same effect as the original except that it would run faster. Executing "ORL C,P2.2" when carry is set will have no observable effect except to waste some number of cycles (two CPU cycles totaling 24 clock cycles on an 8051 if I recall correctly; likely a different number on some other variants). Likewise with executing "ANL C,P2.5" when carry is clear. Although there may be some kinds of processor where a request to read some I/O locations would have some observable effect, I don't think any 8051-style processor has ever had such behavior for any bit-addressable I/O locations, much less for bits of P2.

Perhaps the purpose of the code was to demonstrate the ORL C,bit and ANL C,bit instructions, but this seems like a weird example to demonstrate them.


The assembly code given is likely compiler-generated. It is the unoptimized version of the following C statements, where P2_2 and P2_5 are the bit-addressable objects:

P2_2 |= 1;
P2_5 &= 0;

This may seem equivalent to P2_2 = 1; and P2_5 = 0;, but it isn't if the bit-addressable registers are volatile objects. A read-modify-write operation on a volatile object must perform the read and the write, in that order. This ensures that any side-effects from reading or writing the register actually occur.

Although I know of no 8051 bit-addressable register with side-effects, a compiler cannot assume there isn't or won't ever be one.