C++ — Logical operators and bounds checks
The built-in && operator short-circuits from left to right. Check both ends of a signed index range before converting it to an unsigned array position.
A simple example
Test two conditions
- Start with n is 2
- Do this Greater than 0 and less than 3?
- Result yes
#include <iostream>
int main() {
int n = 2;
if (n > 0 && n < 3) {
std::cout << ("yes") << '\n';
}
}
yes
Operator examples
| Operation | Expression | Result |
|---|---|---|
| Integer division | 7 / 2 |
3 |
| Remainder | 7 % 2 |
1 |
| Comparison | 5 >= 5 |
true |
| Equality | 3 == 4 |
false |
| Logical conjunction | true && false |
false |
| Bit mask | 6 & 3 |
2 |
Guard an indexed lookup
Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. A negative signed index can become a large unsigned value. Here the first comparison rejects it before casting. The second comparison protects operator[].
A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.
Run the example
Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
#include <iostream>
#include <array>
#include <cstddef>
int main() {
const std::array<int, 2> stock{2, 5};
for (int index : {-1, 1, 2}) {
bool take = index >= 0 && static_cast<std::size_t>(index) < stock.size()
&& stock[static_cast<std::size_t>(index)] >= 5;
std::cout << (take ? "take" : "skip") << '\n';
}
return 0;
}
skip take skip
Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.
Try it yourself
Try index 0, then change its value from 2 to 5. How does its classification change?
Check your answer
Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.