QNA > W > What Is The Difference Between Define And Int In Arduino Ide?

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 -

  1. #define A 5 
  2.  
  3. void setup() { 
  4. Serial.print(A); 

The compiler actually compiles -

  1. void setup() { 
  2. 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.

  1. 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).

Di Caughey

Perché Fortnite è così popolare quando è tutto competitivo? :: È possibile essere pagati giocando ai videogiochi?
Link utili