Efficient embedded C part 2

In a previous blog post, we gave tips on writing efficient embedded C code. In this continuation post, you will find more useful advice on writing the most efficient code possible for the embedded space.

Perhaps the most important tip for non-novice embedded C programmers is to make sure that you know your architecture and environment. For your architecture, make sure you know whether or not you are developing for a 16-bit, 32-bit, or 64-bit processor.

Knowledge of the type of processor you are developing code for is useful because it provides insight into the data types you should be using for your embedded project. You can obtain the greatest reduction in code size and fastest possible execution times by choosing the appropriate data type for variables. In an 8-bit processor, the natural data size to use is an 8-bit integer. For 32-bit and 64-bit architectures, specific functions and data types exist to allow for efficient operations on smaller bit-size variables. Intimate knowledge with your architecture’s specific functions will ensure you write the most efficient code possible.

There are three rules for data type selection:
1. Use the smallest type for the job
2. Use unsigned types when appropriate
3. Cast variables from larger types down to smaller types when possible

Use typedefs to get the fixed size of your variable types. Avoid basic types (i.e., char, int, short, long) in application code as these are not unique to any architecture.

Multi-core processors are starting to become more common in the embedded space. If this is the case for you, you can make use of parallel programming techniques to improve the efficiency of your code. A future blog post will be made about writing efficient parallel embedded code: make sure to check back here often for that update.