#define vs. constant int

Status
Not open for further replies.

floating.

Well-known member
Aside from stylistics and readability issues (which I don't want to get into), is there any advantage to use one or the other when defining pins?

#define LED 13
vs.
const int LED = 13;
 
Wikipedia said:
...'const' in the C family of languages differs from similar constructs in other languages in being part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking.

I think the advantage for #define is no memory cost.

I tend to use 'Const' for parameters that are constant during development but which I anticipate becoming variables in subsequent versions.

I believe it is less likely to fail because the code will already have explicit typed data wherever it was used.
 
Oh... for PINs and other multiple assignments the big advantage is a constant array can be looped.
 
I think the advantage for #define is no memory cost.
This isn't the case. The compiler will optimize the constant value into the code without reserving memory for it.

It's good form to avoid #defines whenever possible with modern compilers. The compiler will use the type information for the constant to flag any cases where you might be using mismatched types unsafely.
 
In general, it's better to avoid the preprocessor because the compiler provides far better checking than the preprocessor, and though you don't want to get into it, you can be more specific about your intentions with the compiler. There are exceptions.
 
This isn't the case. The compiler will optimize the constant value into the code without reserving memory for it.
That's good to know.

The compiler will use the type information for the constant to flag any cases where you might be using mismatched types unsafely.
I don't remember ever using these pin definitions aside from in various mode()/read()/write() functions, so I don't see much possibility for unsafe usage.

Now, with other constants such as FREQUENCY or MAX_SPEED that are likely to be used in some kind of computation, type may very well come into play.
 
Status
Not open for further replies.
Back
Top