r/ArduinoInEducation • u/Hubey3270 • Nov 29 '24
Help with uint8_t
What can I only get my defined items to work if I do "#define ..." but when I attempt to do "const byte ..." it ignores me? Any suggestions?
1
Upvotes
View all comments
Show parent comment
3
u/gm310509 Nov 30 '24
No worries, to summarise, you can use something like the following - the exception is the code with
_problemin it:One thing that is important to understand is why (or how) things work the way that they do.
While a complex subject, the C/C++ compiler consists of a number of steps when compiling your program. One of those is known as the "preprocessor".
The preprocessor is mostly responsible for processing directives that begin with a "#". Commonly seen ones are
#includeand#define, but there are several others.The
#definedirective works like a "search and replace", but is more sophisticated than that. It is actually a macro substitution. I explain this in my third "Post starter kit video" which is available on Patreon. You can see the first two in the series (for free) on my YouTube video. The full series is described in my reddit post: Getting started with Arduino - next steps after the starter kit. There is a link to the playlist in that post.So, why does the
_problemcode work?Well if we simplisticly think of
#defineas a search and replace mechanism (which works just fine in this situation), then the code becomes:As for the
const byte ...stuff, these are not handled by the pre-processor.Rather these are handled by phase 1 of the compilation process - which follows the pre-processor.
Since the
const byte ...stuff is handled by the C compiler proper, these must conform to the rules of variable declarations for C. and that is why it must be like this:Decoding the above:
const,byte,EMERGENCY_BROADCAST,= 12;is required.NB: the above is a simplified syntax definition, there are plenty of other variations allowed.
You might want to have a look at: https://docs.arduino.cc/language-reference/#structure
This page provides some links to very basic C/C++ language structure including the #define.
For variable definitions, have a look at another tab on the same page: https://docs.arduino.cc/language-reference/#variables