0
0
C++programming~5 mins

Return inside loops in C++

Choose your learning style9 modes available
Introduction

Using return inside loops lets you stop the whole function early when you find what you need.

When searching for a specific item in a list and you want to stop once found.
When checking conditions repeatedly but want to exit immediately if a condition is met.
When processing data and you want to return a result as soon as possible.
When you want to avoid unnecessary work after a certain point in a loop.
Syntax
C++
for (initialization; condition; update) {
    if (some_condition) {
        return value;
    }
    // other code
}

The return statement ends the function immediately, even if inside a loop.

Any code after return inside the loop or function will not run.

Examples
This loop returns 3 as soon as i equals 3, stopping the function.
C++
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        return i;
    }
}
This infinite loop returns 1 when check() is true, ending the function.
C++
while (true) {
    if (check()) {
        return 1;
    }
    // keep looping
}
Sample Program

This program looks for the first even number in the array. It returns immediately when it finds 8, so it stops checking after that.

C++
#include <iostream>

int findFirstEven(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        if (arr[i] % 2 == 0) {
            return arr[i];
        }
    }
    return -1; // no even number found
}

int main() {
    int numbers[] = {1, 3, 7, 8, 10};
    int result = findFirstEven(numbers, 5);
    std::cout << "First even number: " << result << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Remember, return exits the whole function, not just the loop.

If you want to stop only the loop but continue the function, use break instead.

Summary

return inside loops stops the entire function immediately.

Use it to exit early when you find what you need.

Code after return will not run.