Constants

A constant is a value that never changes. In the Arduino programming language, we have two ways to declare constants. We can use the const keyword or the #define component.

The #define component enables us to give a name to a constant value prior to the application being compiled. The compiler will replace all references to these constants, with the assigned value, prior to the application being compiled. This means that the defined constants do not take up any program space in memory, which may be an advantage if you are trying to squeeze a large program into an Arduino Nano.

The #define component does have some drawbacks where the biggest drawback being if the name that is defined for the constant is also included in some other constant or variable name then the name would be replaced by the value defined in the #define component. For this reason, when I use the #define to define a constant I usually use all capital letters for the name.

The following code shows how to use the #define component. You will note in the following code that with the #define component there is no semicolon at the end of the line. When using a directive like #define, you do not need to use a semicolon:

#define LED_PIN 8

The second way to declare a constant is to use the const keyword. The const keyword is a variable qualifier that modifies the variable's behavior making it read-only. This will enable us to use the variable exactly as we would any other variable except that we are unable to change the variable's value. If we attempted to change the value, we would receive a compile-time error.

The following code shows how to use the const keyword:

const float pi = 3.14; 

The const keyword is generally preferred of the #define component; however, with devices with limited memory the #define can be used. Now let's see how we can perform math functions in the Arduino programming language.