#define vs. const variable

Hi,

I am currently working on my first library and have a quick question. In the Arduino library tutorial seen here: http://arduino.cc/playground/Code/Library The .cpp file, on line 3, has a const variable declaration (const byte LED_PIN = 13;)

Now, when I look at almost every other library, they very rarely have variable declarations like this. Instead they use the #define method to declare the same thing (or so it appears).

So my question is, what is the difference between using these two different methods? Does the #define method save on available memory maybe?

Does the #define method save on available memory

Yes but not by much. Using const will flag up errors if you try and change the value but that's all. I prefer the #define myself but plenty of purists will disagree.

Sparked: So my question is, what is the difference between using these two different methods? Does the #define method save on available memory maybe?

Only saves memory in oddball cases. In normal use, the memory use is the same. Using 'const' is much safer simply because it uses the compiler not the preprocessor. The preprocessor is a dumb text-substitution engine, chewing blindly through text and making substitutions. The compiler knows everything that's going on, so it will be much smarter about what it does with your variables. It will save you (and users of your library) from making certain dumb mistakes.

See http://arduino.cc/forum/index.php/topic,88087.0.html and links

The only way to answer the question... http://www.random.org/coins/?num=1&cur=60-usd.0025c-pa

Bah, sorry. I don't know why I couldn't find those other threads started this month. Thanks for the help.

A #define is a macro, this means at compile time, the compiler finds every occurance of the macro, for example MY_DEFINITION and replaces it with whatever is assigned to it in the #define statement.

A variable defined as const has a physical memory address, which means that at run time the value of this location is loaded into a register before reading.

A #define is always 'inline', in terms of storage, it depends what your macro is doing. By nature of the fact that macros cannot manipulate dynanic data the compiler should resolve the macro to an absolute value. I'm not sure that either method would be any more different in terms of storage but for speed I would go for the #define everytime.