Advanced Coding Tips

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

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

Trap #12: Overflowing an integer.

eg.

Wrong! …

 

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:

 

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:


Or, better still:


 

 


 

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

Bad:

Good:

 

 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:

 

Leave a Reply

Your email address will not be published.