Detecting and preventing infinite loops is an important aspect of writing robust and reliable C++ code. Here are a few techniques you can use to identify and avoid infinite loops:
#include <iostream>
int main() {
int count{0};
while (true) {
++count;
if (count > 1000) {
std::cout << "Potential infinite loop"
" detected. Breaking...\n";
break;
}
}
}
Potential infinite loop detected. Breaking...
In this example, the loop variable i
 is not incremented, causing an infinite loop:
#include <iostream>
int main() {
int i{0};
while (i < 10) {
std::cout << i << "\n";
// Missing increment statement
}
}
0
0
0
...
Example using std::chrono
:
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
auto start = steady_clock::now();
while (true) {
auto current = steady_clock::now();
auto duration = duration_cast<seconds>(
current - start);
if (duration.count() > 5) {
std::cout
<< "Timeout exceeded. Terminating...\n";
break;
}
}
}
Timeout exceeded. Terminating...
By applying these techniques and being cautious when writing loop conditions, you can detect and prevent infinite loops in your C++ code, ensuring more stable and predictable program behavior.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break