Why does const matter?

Let’s learn why making const variables or parameters matters.

We'll cover the following

Explanation

We’ll also encounter some developers who will be reluctant to declare variables, functions, parameters, etc. as const “because it doesn’t matter anyway.”

In his talk “Rich Code for Tiny Computers”, Jason Turner argued for the usage of const through an example.

The Example

In Jason Turner’s example, there is a static array of 16 colors, where each color is represented by a Color object, which takes an ID and the red, green, and blue (RGB) components encoded as integers.

Then, the program performs a simple operation on the array of colors… However, the compiler had 350 instructions to complete in this single operation.

During the talk, Turner asked the audience if there were some best practices that they could use to reduce the required overhead. Some suggested using constexpr, others recommended precomputed data, but the solution was even simpler.

Turner just had to add const to the declaration, and the number of instructions went down from about 350 to 5. No typo there, from 350 to 5! Changing static std::array<Color, 16> colors {{...}} to static const std::array<Color, 16> colors {{...}} reduced the required number of instructions by a factor of 70.

“So if you don’t currently use const anywhere you can, I bet you will after this talk!”, Turner said as he concluded the talk.

Get hands-on with 1400+ tech skills courses.