#define

Description

#define is a useful C++ component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don't take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.

This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text).

In general, the const keyword is preferred for defining constants and should be used instead of #define.

Syntax

#define constantName value

Parameter Values

  • constantName: the name of the macro to define.
  • value: the value to assign to the macro.

Example Code

#define LED_PIN 3 void setup() { pinMode(LED_PIN, OUTPUT); // The compiler replaces LED_PIN with 3 } void loop() { digitalWrite(LED_PIN, HIGH); // The compiler replaces LED_PIN with 3 delay(1000); digitalWrite(LED_PIN, LOW); // The compiler replaces LED_PIN with 3 delay(1000); }

※ NOTES AND WARNINGS:

There is no semicolon after the #define statement. If you include one, the compiler will throw cryptic errors further down the page.

#define LED_PIN 3; // this is an error

Similarly, including an equal sign after the #define statement will also generate a cryptic compiler error further down the page.

#define LED_PIN = 3 // this is also an error

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES