/*Global Variables:
Definition: A global variable is one that is declared outside of all functions.
Scope: Its scope is throughout the file and can be accessed from any function within the file.
If declared as extern, it can be accessed from other files as well.
Usage: Global variables are used when multiple functions need to access the same piece of data.
Declaration (in C/C++): It's declared outside of all functions, usually at the top of the file.
Local Variables:
Definition: A local variable is one that is declared within a function or a block.
Scope: Its scope is limited to the function/block where it is defined, and
it's destroyed once the function/block exits.
Usage: Local variables are used for temporary storage and are generally preferred to minimize
the variable's scope, making the program easier to understand and debug.
Declaration (in C/C++): It's declared within a function or a block
*/
// Global variable - Lives in Data Segment if initialized
int globalVar = 10;
// Global variable - Lives in BSS Segment if uninitialized
int uninitGlobalVar; // Default initialization value is 0 ( initialized to 0 in BSS segment)
void setup() {
// Local variable - Lives in Stack
int localVar = 20;
// Dynamic variable - Lives in Heap
int *dynamicVar = new int(30);
Serial.begin(9600);
// Print all variables
Serial.println("Variables:");
Serial.print("Global variable: ");
Serial.println(globalVar);
Serial.print("Uninitialized Global variable: ");
Serial.println(uninitGlobalVar); // Should be automatically initialized to zero
Serial.print("Local variable: ");
Serial.println(localVar);
Serial.print("Dynamic variable: ");
Serial.println(*dynamicVar);
// Don't forget to free the dynamically allocated memory
delete dynamicVar;
}
void loop() {
// Empty loop
}