I have this CommandHandler type that relies on the Serial object. I want to be able to declare the variable in global scope, but instantiate it in the setup() method after serial comms have been started.
A variable is completely different from instantiating an object.
If you declare a variable this variable will be assigned the value zero if you don't assign any value at the line you declare the variable.
You can assign any value to a variable that fits into the variable at any place of your code
int myIntegerVariable; // declaration of a variable without assigning a value
void setup() {
myIntegerVariable = 123; // assigning a value to the variable
maybe you are confusing the term "variable" with something else?
best regards Stefan
I'm coming from a easier languages than C. In .NET, Java or JavaScript I would call that thing a variable (or a constant if it's declared as such). In those languages, if I declare that token, without explicitly giving it a value then the value will be whatever default is, i.e. 0 for numbers, false for booleans, null for reference types etc.
What I want is to declare the token that I would use to access the instance of CommandHandler as global, but only instantiate the object in the setup() method.
In C/C++, declaring a variable assigns memory addresses to it. Whether it is initialized to some value depends on the circumstances.
I don't recall all the rules, but global numerical variables are initialized to zero. In functions, a declared, but uninitialized variable will usually contain garbage.
Consult the many on line references for the details.
The "Serial" object exists in global scope after you #include <Arduino.h>. It is not clear how you are trying to use it. Since the error is in "main.cpp" I suspect you forgot to #include <Arduino.h> before trying to use the names it defines.
Would you mind explaining when the address and value is assigned to x in this purposely incomplete code, which compiles with the expected warning, runs and prints "x = 0"?
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial);
int x;
Serial.print("x = ");
Serial.println(x);
}
void loop() {}
I DO NOT rely on luck, but this VERY PURPOSEFUL example printed x = 0. I would expect it to print garbage at other times, as mentioned in my first post.
I'm awaiting an answer on when the memory address and value is assigned.