Pages: [1]   Go Down
Author Topic: #define vs variables?  (Read 610 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
Karma: 0
Posts: 70
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm almost positive this must have been discussed somewhere before, but my searches didn't turn anything up, so my apologies.

I was wondering why it seems to be the convention here to use integers to define pin mappings. Wouldn't #define be more space efficient, since the pins presumably aren't changing? And, if there is a good reason for using a variable, why not use a smaller one, like a byte, rather than an int?

That said, in general, why should one use a #define over a variable, and vice versa?

Thanks for indulging a newbie!  smiley

Offline Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Good questions.

Using a #define is a little more efficient.
In the Blink example sketch, replacing:
   int ledPin = 13;
  #define ledPin 13

actually reduces the code size by  8 bytes.

but when you do need to manipulate the value as a variable (i.e. looping through pins in a for loop) then declaring the variable as byte is a little more efficient then as an int.

I think int is used in the examples so newbies don't get confused seeing types they are not yet familiar with.

There are many factors to take into consideration when choosing #defines over variables. The pre-processor can optimize constants at compile time so use them when you can. but the pre-processor does not understand the C language so the behavior of your code can be different from a seemingly similar variable expression. Also, #defines can be a little difficult to debug so using a variable is no bad thing unless efficiency is a priority.
« Last Edit: December 23, 2007, 12:11:47 pm by mem » Logged

Pages: [1]   Go Up
Jump to: