5

Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the #define command to declare pins, while some others simply use const int for the same.

My question is, what's the difference between the two, and which one should be preferred for use?

Mikael Patel
  • 7,989
  • 2
  • 16
  • 21
YaddyVirus
  • 292
  • 1
  • 6
  • 21

1 Answers1

1

"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.

"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.

Example:

#define A 5
int dummy_integer = A

... will be preprocessed as...

int dummy_integer = 5

... and the compiler will read this statement.

However, if I remember good, you can always overwrite a preprocessor directive as follows:

#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A  

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").