Pages: [1]   Go Down
Author Topic: programming tip: int vs. byte vs. #define  (Read 1922 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Faraday Member
Karma: 8
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I've noticed several arduino programs (sketches) that start out

int myInputpin = 3;

void setup()

What we've done here is to use 2 bytes of RAM, which can be a scarce resource on a microcontroller, in order to store a value that couldn't possible be more than 28, and worse one than that it will never change!

If you know the range of a value will be limited, make the type reflect that:  a byte type can hold 256 values, but only occupies (you guessed it) one byte.

Even better, if the value is a constant that never changes (will you suddenly change that input to a different pin during program execution?  probably not!) use a constant to represent that value, and use a #define preprocessor directive to give a meaningful name to that constant:

#define MYINPUTPIN 3
this way we have a symbolic name for the value and we save RAM (to store that huge array we want to have in some other part of our program).

The all-caps MYINPUTPIN is a common style to tell us at a glance that we're dealing with a preprocessor directive, rather than a variable or a function.  Spelling it "myInputpin" would work just fine, but it may cause confusion especially if others use your code and are expecting the all-caps convention.

Sorry for the lecture.  smiley


Pages: [1]   Go Up
Jump to: