diff --git a/examples/at/at.ino b/examples/at/at.ino new file mode 100644 index 0000000..6c16a1e --- /dev/null +++ b/examples/at/at.ino @@ -0,0 +1,39 @@ +/** + * @file at.ino + * @author Alexander Tonn (https://github.com/AlexanderTonn) + * @brief This example shows the usage of ::at Operator + * ! If the inserted index is out of range, the program will return the value of the last index + * ! Code tested with Arduino MEGA2560 + * @date 2024-01-05 + */ + +#include "Array.h" + +Array test1 = {{34,32,66,34,35,23,44,78,56,240,2323,234}}; +const Array test2 = {{1,7,3,7,35,23,44,78,56,240}}; +Array test3 = {{1.45,425.0,234.9,234.4,567.4}}; +Array test4 = {{false,false,true,true,false,true,true,true}}; +void setup() +{ + Serial.begin(9600); + + // Try to Access an out of range index + Serial.println(test1.at(16)); + Serial.println(test2.at(14)); + Serial.println(test3.at(10)); + Serial.println(test4.at(20)); + + Serial.println("########"); + + //Try to Access an in range index + Serial.println(test1.at(5)); + Serial.println(test2.at(3)); + Serial.println(test3.at(2)); + Serial.println(test4.at(6)); + +} + +void loop() +{ + +} \ No newline at end of file diff --git a/src/Array/ArrayDefinitions.h b/src/Array/ArrayDefinitions.h index d6bd5a3..f0e6002 100644 --- a/src/Array/ArrayDefinitions.h +++ b/src/Array/ArrayDefinitions.h @@ -66,14 +66,32 @@ template const T & Array::at(size_t index) const { - return values_[index]; + auto arraySize = sizeof(values_)/sizeof(values_[0]); + + if(index < 0 || index >= arraySize) + { + Serial.println(" Array Index out of Range! Last valid Index will be returned."); + + auto outOfRangeIndex = arraySize-1; + return values_[outOfRangeIndex]; + }else + return values_[index]; + } template T & Array::at(size_t index) { - return values_[index]; + auto arraySize = sizeof(values_)/sizeof(values_[0]); + if(index < 0 || index >= arraySize) + { + Serial.println(" Array Index out of Range! Last valid Index will be returned."); + + auto outOfRangeIndex = arraySize-1; + return values_[outOfRangeIndex]; + }else + return values_[index]; } template