What is the best method - digitalRead

Hi guys, just wondering if there is a difference between the two methods shown below - from a memory/efficiency/good practice point of view.

int value;     //int or boolean

value = digitalRead(somePin);

if(value == HIGH){
  //do something

or the other method:

if(digitalRead(somePin) == HIGH){
    //do something


Is there any difference what would be the best practice.

The difference is that the first method requires a two byte variable (use "byte" instead = one byte variable), and enables you to use the reading multiple times (eg. storing last pin state). The last requires no variable but the reading is only valid as a one time statement.

Thanks, correct me if I wrong - so there is not difference if memory is not an issue correct?

In general an extra variable costs memory, so I would prefer the second one.

If the value stored in the variable is used in several places (not likely with digitalRead), i prefer the first one because the result is consistent.

And I prefer to save the value from digitalRead() into a variable because then I can print the variable if I need to for debugging purposes.


If value is declared locally, it will exist only on the stack for the duration of it’s scope and will therefore ‘appear’ to consume no memory during compile. If it is being used elsewhere for testing/debug (globally), you should probably come up with a more meaningful name.

On top of that, the compiler is smart enough to optimize away the variable, so you shouldn't see any difference in memory usage (including the stack) between your two examples.