Go Down

Topic: #define vs variables? (Read 714 times) previous topic - next topic

A._Square

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!  :)

mem

#1
Dec 23, 2007, 06:10 pm Last Edit: Dec 23, 2007, 06:11 pm by mem Reason: 1
Good questions.

Using a #define is a little more efficient.
In the Blink example sketch, replacing:
  int ledPin = 13;
with:
 #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.

Go Up