Control Flow
Break and Continue
continue skips to the next loop pass, while break stops the loop.
Break and Continue
break_continue.cpp
#include <iostream>
int main() {
int stopAt = ;
int values[6] = {2, -1, 4, 6, -3, 8};
int total = 0;
for (int value : values) {
if (value < 0) {
continue;
}
if (value == stopAt) {
break;
}
total += value;
}
std::cout << "stopAt=" << stopAt << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int stopAt = ;
int values[6] = {2, -1, 4, 6, -3, 8};
int total = 0;
for (int value : values) {
if (value < 0) {
continue;
}
if (value == stopAt) {
break;
}
total += value;
}
std::cout << "stopAt=" << stopAt << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int stopAt = ;
int values[6] = {2, -1, 4, 6, -3, 8};
int total = 0;
for (int value : values) {
if (value < 0) {
continue;
}
if (value == stopAt) {
break;
}
total += value;
}
std::cout << "stopAt=" << stopAt << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
break
`break` exits the nearest loop immediately.