Dependancies
Pre-requisites
Buy the components
pass-by-value-reference-arduino-esp32c3.ino
// Demonstrates the difference between pass by value
// and pass by reference in C++ using Arduino ESP32-C3
void setup() {
Serial.begin(115200);
int originalValue = 5;
passByValue(originalValue);
Serial.print("Pass by Value: ");
Serial.println(originalValue); // Outputs 5
passByReference(originalValue);
Serial.print("Pass by Reference: ");
Serial.println(originalValue); // Outputs 10
passByReferenceWithPointer(&originalValue);
Serial.print("Pass by Reference with Pointer: ");
Serial.println(originalValue); // Outputs 15
}
void loop() {
}
void passByValue(int value) {
value = 10;
}
// Linting error:
// Is this a non-const reference?
// If so, make const or use a pointer: int &value
void passByReference(int &value) {
value = 10;
}
void passByReferenceWithPointer(int *value) {
*value = 15;
}
BOARD?=esp32:esp32:esp32c3
PORT?=/dev/cu.SLAB_USBtoUART*
BUILD=build
.PHONY: default lint all flash clean
default: lint all flash clean
lint:
cpplint --extensions=ino --filter=-legal/copyright,-runtime/references *.ino
all:
arduino-cli compile --fqbn $(BOARD) --output-dir $(BUILD) ./
flash:
arduino-cli upload --fqbn $(BOARD) --port $(PORT) --input-dir $(BUILD)
clean:
rm -r build
This simple code the difference between pass by value and pass by reference in C++ using Arduino ESP32-C3.
Aspect | Pass-by-Value | Pass-by-Reference | Pass-by-Reference with Pointers |
---|---|---|---|
Syntax | int value |
int &value |
int *value |
Usage | Operates on a copy of the variable | Direct access to variable | Use of address-of (& ) and dereference (* ) operators |
Modification | Does not affect original variable | Affects original variable | Affects original variable |
Initialization | N/A | Must be initialized | Can be null |
Readability | Most readable, simplest | More readable and less error-prone | Requires explicit pointer handling |
Compatibility | Works in both C and C++ | C++ only | Works in both C and C++ |
Performance | Copies data (may be slower for large data) | No copying, efficient | No copying, efficient |