Sub topic 5
Constants with const and #define
This chapter covers the two ways to give a fixed value a name in an Arduino sketch: the const qualifier and the #define preprocessor directive. It assumes you can write a sketch with setup() and loop(), declare variables with types such as int, byte, and unsigned long, and use pinMode() and digitalWrite(). It also assumes you have used the Serial Monitor to print values.
Why name a fixed value
A bare number in code is called a magic number. Consider this line:
digitalWrite(7, HIGH);A reader cannot tell what pin 7 is wired to. If the wiring changes, you must find every 7 that means "the alarm LED" and skip every 7 that means something else. A named constant fixes both problems:
const byte alarmLedPin = 7;
digitalWrite(alarmLedPin, HIGH);The name documents the intent, and you change the value in one place. A constant also stops you from assigning to the value by accident, because the compiler rejects the assignment.
Constants with const
Put const before a type to declare a variable that cannot change after initialization.
const byte buttonPin = 2;
const int threshold = 512;
const float supplyVoltage = 5.0;Three rules apply:
- You must give the value in the declaration.
const int limit;is an error because it could never be set later. - Any later attempt to change it, such as
threshold = 600;, causes a compile error. This is a feature. The error appears on your computer, before the code reaches the board. - A
consthas a type, so the compiler checks how you use it. Passingconst byte buttonPinwhere a function expects abyteworks. Passing aconst floatwhere anintis expected triggers the normal conversion rules.
Scope of a const
A const follows the normal scope rules from the earlier chapter on scope and lifetime. A const declared above setup() is visible to the whole sketch. A const declared inside a function exists only in that function. Prefer the narrowest scope that works. A value used by one function belongs inside that function.
Memory cost
On an Uno (ATmega328P), a const of a simple type usually costs no RAM. The compiler substitutes the value directly into the machine instructions where you use it, so no storage is reserved. A plain global int pin = 7; may take 2 bytes of RAM and each read costs an instruction to fetch it. Using const is therefore both safer and often cheaper.
The exception is arrays. A const array of values still occupies RAM on AVR boards unless you also mark it PROGMEM, which stores it in flash. Making an array const protects it from modification but does not save memory by itself.
Constants with #define
#define is not C++ code. It is an instruction to the preprocessor, a text-processing step that runs before the compiler. The preprocessor finds every occurrence of a name and replaces it with the text you gave.
#define ALARM_LED_PIN 7
#define SAMPLE_COUNT 10Notice what is missing: there is no type, no =, and no semicolon. The preprocessor does not understand types. It only copies text. After preprocessing, the compiler sees digitalWrite(7, HIGH); and never learns that a name ever existed.
Pitfall: the stray semicolon
Because the replacement is plain text, a trailing semicolon becomes part of the replacement:
#define ALARM_LED_PIN 7;
// digitalWrite(ALARM_LED_PIN, HIGH); becomes
// digitalWrite(7;, HIGH); -> compile errorThe error message points at the line where you used the name, not at the #define, which makes it confusing to track down.
Pitfall: missing parentheses
When the replacement is an expression, the text lands inside other expressions, and operator precedence can change the result. This sketch shows it:
#define LED_COUNT 3 + 1
void setup() {
Serial.begin(9600);
Serial.println(2 * LED_COUNT);
}
void loop() {
}You might expect 8. The preprocessor produces 2 * 3 + 1, which is 7. Writing #define LED_COUNT (3 + 1) fixes it. A const byte ledCount = 3 + 1; never has this problem, because the compiler evaluates the initializer to a single value first.
No scope, no type checking
A #define takes effect from its line to the end of the file, regardless of functions or blocks. It ignores scope entirely. If a library defines a macro with the same name as one of your variables, the preprocessor replaces your variable's name too. This leads to strange errors. Macros also have no type, so the compiler cannot warn you when you use a value in the wrong kind of place.
const versus #define
| Feature | `const` | `#define` |
|---|---|---|
| Handled by | Compiler | Preprocessor (text substitution) |
| Has a type | Yes | No |
| Respects scope | Yes | No, applies to the rest of the file |
| Syntax | `const byte pin = 7;` | `#define PIN 7` (no `=`, no `;`) |
| Error messages | Point at the real problem | Often point at the place of use |
| RAM use (simple types) | Usually none | None |
| Conditional compilation | Not possible | Possible with `#if` and `#ifdef` |
For ordinary values such as pin numbers, thresholds, and timing intervals, use const. The Arduino project's own style guidance also recommends const over #define for constants.
Where #define is still the right tool
#define earns its place when you need the preprocessor's ability to include or exclude code. A common case is a debug switch:
#define DEBUG 1
const byte sensorPin = A0;
const int threshold = 512;
const unsigned long loopDelayMs = 500;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
int reading = analogRead(sensorPin);
digitalWrite(LED_BUILTIN, reading > threshold ? HIGH : LOW);
#if DEBUG
Serial.println(reading);
#endif
delay(loopDelayMs);
}When DEBUG is 1, the Serial.println line is compiled in. Set it to 0 and the preprocessor removes the line before the compiler sees it, so the final program is smaller and faster. A const cannot do this, because a normal if on a const still leaves the code in your source, and its handling depends on the optimizer.
This sketch also shows the combination most sketches use: const for values, #define only for the build switch.
Built-in constants
Arduino already defines many constants you have been using:
HIGHandLOWfor pin levels.INPUT,OUTPUT, andINPUT_PULLUPfor pin modes.LED_BUILTINfor the board's onboard LED pin. Its value depends on the board you selected.A0,A1, and so on for analog pins.trueandfalsefor Boolean values.
Use these names instead of numbers. digitalWrite(13, 1) works on an Uno but hides meaning, and LED_BUILTIN also keeps working on boards where the onboard LED is not on pin 13.
Edge cases and common errors
Integer overflow in constant expressions
On an Uno, int is 16 bits and holds at most 32767. This constant overflows:
const int oneMinuteMs = 60 * 1000; // 60000 does not fit in a 16-bit intThe multiplication happens in int arithmetic before the result is stored, and the value wraps to -5536. Use unsigned long and the UL suffix so the arithmetic is done in the wider type:
const unsigned long oneMinuteMs = 60UL * 1000UL;The same applies to #define. Write #define ONE_MINUTE_MS (60UL * 1000UL) with parentheses and suffixes.
const arrays and pointers
const byte ledPins[] = {3, 4, 5, 6}; makes each element read-only. You can still loop over the array and read it as shown in the arrays chapter. Writing ledPins[0] = 9; is a compile error. For arrays of text, const char* const names[] means both the characters and the pointers cannot change. You will rarely need that form, but you will see it in library code.
Related integer constants: enum
When several constants form a set, such as program states, an enum is clearer than several const lines:
enum State { IDLE, RUNNING, FAULT };The names are assigned the values 0, 1, and 2 in order. The compiler can then check that you use them as a group.
constexpr
The Arduino toolchain uses a modern C++ standard, so constexpr is available. It tells the compiler that a value must be computed at compile time, as in constexpr unsigned long oneMinuteMs = 60UL * 1000UL;. For simple constants, const and constexpr behave the same in practice, so using const is fine. Learn constexpr when you write functions that must run at compile time.
Naming conventions
Pick a style and keep it. Common choices are camelCase for const values (alarmLedPin) and UPPERSNAKECASE for macros (DEBUG). Using capitals for macros is useful because it warns readers that the name is text substitution with no scope.
Summary of rules
- Use
constwith an explicit type for pin numbers, thresholds, and intervals. - Use
#definefor build switches and conditional compilation. - Wrap every expression in a macro in parentheses.
- Use
ULsuffixes for millisecond calculations. - Declare constants in the narrowest scope that works.
Exercise
A sketch contains #define SAMPLES 4 + 6 and later calls Serial.println(SAMPLES * 2);. What number prints, and how would you change the code so it prints 20?
Show answer
It prints 16. The preprocessor turns the expression into 4 + 6 * 2, and multiplication happens first, giving 4 + 12. To print 20, add parentheses, #define SAMPLES (4 + 6), or better, replace the macro with const byte samples = 4 + 6;.
Exercise
On an Arduino Uno, you write const int timeoutMs = 45 * 1000;. Why is this wrong, and what is the corrected declaration?
Show answer
The int type is 16 bits on an Uno, so it holds at most 32767. The product 45000 overflows and wraps to a negative number. The corrected declaration is const unsigned long timeoutMs = 45UL * 1000UL;.
Exercise
Name one task that #define can do and const cannot, and give a short example.
Show answer
Conditional compilation. For example, #define DEBUG 1 followed by #if DEBUG around a Serial.println call includes or removes that line from the compiled program. A const cannot make the preprocessor drop the code.