I wrote a code for to toggle the port that is given below #include<reg51.h> sbit CLOCK = P0^2; void main() { while(1) { CLOCK = CLOCK^1; } } its not toggling in the IDE please guide me Mahesh
May be. But I have used like this and it is error free.
but have you tried
CLOCK = ~CLOCK;
CLOCK = !CLOCK;
You please compile these two codes in Keil and watch the opcode generated thro disassembly window. You can fine which is better.
#include<reg51.h> sbit CLOCK = P0^2; void main() { if(CLOCK) { CLOCK = 0; } else { CLOCK = 1; } }
void main() { CLOCK = CLOCK ? 0 : 1; }
The code size for yours is 25 and mine is 24. In the best case, that is if the clock is high, my code will work 2 cycles faster. You can place breakpoints in both the cases, if you want.
Of course the 'if' version and the ternary operator will almost certainly be the same. But that's not what I said - I said that using the complement operator is likely to give "better" code.
You can fine which is better. On any halfway sane compiler, the two bits of code should produce exactly the same assembly output. Dont see the size of the c file. But that's the whole point. Toggling a bit is simple enough that it can be put into one line of code instead of eight, ... unless you get paid by lines of code, in which case the first solution is to be preferred. Unnecessarily bloating the source code makes maintenance more difficult.
You are going to place the c code in your hard disk or any thing else. But the opcode is going to reside in FLASH. One byte of FLASH is costlier than some 50 bytes of hard disk. And no one can pay for the execution time. Comment statements are there to give the understanding.
So try:
CLOCK ? (CLOCK = 0) : (CLOCK = 1);
this is basicallt the same as
if (var = TRUE) { var = FALSE: } the above is the simple example and I can not tell how many times I have seen this idiocy/ Erik