ZakKemble / NWatch

N|Watch - DIY Digital Wristwatch
https://blog.zakkemble.net/diy-digital-wristwatch/
GNU General Public License v3.0
340 stars 126 forks source link

Removed some pretty pointless code #1

Closed SamTebbs33 closed 8 years ago

ZakKemble commented 8 years ago

If ledFlash was not static then it would have been pointless, but the way it is at the moment makes it alternately light up the red and green LEDs. Your code just makes it light up the green LED.

SamTebbs33 commented 8 years ago

Correct me if I'm wrong, but here's my understanding of the execution in that block of code:

  1. The variable is set to LED_GREEN.
  2. It is then compared with LED_GREEN (which is to my understanding pointless, as the line above sets it to LED_GREEN) and if the comparison was successful, sets it to LED_GREEN (which it already is).

According to my understanding, this code is pointless as it compares a variable and a value that has already been set to that value, and then sets it to that value again.

ZakKemble commented 8 years ago

You're forgetting about the variable being declared static. Static is the bit that makes this block of code not pointless :P

  1. At the very beginning of the program 1 byte of RAM is permanently allocated to storing the variable (the static part does this) and is initially set to LED_GREEN.
  2. When the block of code is ran the variable is compared with LED_GREEN, which if it is then it is set to LED_RED. If the variable is not LED_GREEN (probably because it is LED_RED) then it is set back to LED_GREEN. This makes it alternate between the two values.
SamTebbs33 commented 8 years ago

Oh I see, I personally don't find this one of the most semantic and readable elements of C, as the fact that the variable assignment is inside a code block implies that it happens each time that code block is run.