What is the difference between define and int in Arduino IDE?
#define is almost literally a find-and-replace. The compiler (more accurately the pre-processor) does that that before actually compiling your code.
So if you write -
- #define A 5
- void setup() {
- Serial.print(A);
- }
The compiler actually compiles -
- void setup() {
- Serial.print(5);
- }
If you declare a variable (eg. “int a;”), you are defining a quantity that will be kept in memory, and you can change it.
If you write “int a = 5;” that defines a variable with an initial value of 5 (and then you can set it to anything you want).
In general, in C++ (which Arduino is based on), the best way to define constants is to use the “const” keyword, because then the compiler will be able to do a bunch of checks for you to make sure you aren’t doing something silly. It won’t be able to do that with #define, because that’s just textual find-and-replace.
- const int A = 5;
Unfortunately you’ll still see a lot of #defines in Arduino code you’ll find online, because a lot of the code you’ll find are written by beginners who may not understand how C++ constants work (or how compiler optimizations work).