Advanced Coding Tips

(expression) ? (true-value) : (false-value)

————————————————–

Trap #12: Overflowing an integer.

eg.

Wrong! …

unsigned long secondsInDay = 60 * 60 * 24;

 

Small literal constants (like 60) are treated by the compiler as an int type, and have a maximum value of 32767. Multiplying such numbers together has a maximum value of 32767 still.
Correct:

unsigned long secondsInDay = 60UL * 60 * 24;

 

The “UL” suffix promotes the number to an unsigned long.
http://www.gammon.com.au/forum/?id=12146

 


 

Using a const rather than a #define

has various advantages, including the one of consistency. Now the semicolon and “=” symbol are required. This is consistent with the way you write variables. However there is no performance or space penalty for using constants like this (compared to using #define).

Correct:

#define LED_PIN 10

Or, better still:

const byte LED_PIN = 10;

 

 


 

Tip #8: Use “switch/case” rather than lengthy “if” tests

Bad:

if (command == 'A') 
{ // do something 
} 
else if (command == 'B') 
{ // do something 
} 
else if (command == 'C') 
{ // do something 
} else 
{ // unexpected command 
}

Good:

switch (command)
{
case 'A':
// do something
break;

case 'B':
// do something
break;

case 'C':
// do something
break;

default:
// unexpected command
break;
} // end of switch

 

 Advanced Switch Case:

A switch Variation, the Ellipsis Operator ( … )
There will be times when you need a more broad type of switch fall-through. For example, it’s pretty
common to assign grades such that 0 to 59 is an F, 60 to 69 is a D, 70 to 79 is a C, and so on. In this situation,
we want a fall-through that is broader than a single letter. In this situation, we can use the ellipsis operator.
The ellipsis operator allows us to state a range of values for the variable that is expression1 . The following
code fragment shows how this works:
char letterGrade;
int grade;
// some code that gives grade a value between 0 and 100
switch (grade) {
case 0...59:
letterGrade = 'F';
break;
case 60...69:
letterGrade = 'D';
break;
case 70...79:
letterGrade = 'C';
break;
case 80...89:
letterGrade = 'B';
break;
case 90...100:
letterGrade = 'A';
break;
default:
Serial.println("Should never see this.");
break;
}

 

Leave a Reply