Isabella Haidic
PRO
last year
Isabellacountry asked

I wanted to use a range-based for loop instead of a regular for loop: for (double number : elements) { sum = sum + number; } But it didn’t work in my code. I don’t understand why I can’t use it — isn’t it doing the same thing, just in shorter form?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Hi Isabella,

You’re absolutely right — range-based for loops are a great way to simplify your code. But in your case, the reason it doesn’t work likely has to do with how arrays behave when passed to functions in C++.

Here's the issue:

When you pass an array like this:

void find_average(double elements[5]) { ... }

Inside the function, elements is actually treated as a pointer (double*), not a real array. The compiler loses the size information, which the range-based for loop depends on to work.

So this:

for (double number : elements)

won’t work because C++ doesn’t know how many elements to loop over.


✅ How to fix it

Option 1: Use a loop with an explicit size

void find_average(double* elements, int size) {
    double sum = 0.0;
    for (int i = 0; i < size; ++i) {
        sum += elements[i];
    }
}

Option 2: Use std::array or std::vector
These keep size information, so range-based loops work fine:

#include 

void find_average(const std::array& elements) {
    double sum = 0.0;
    for (double number : elements) {
        sum += number;
    }
}

So yes — range-based for loops do the same thing, but they only work when the size of the container is known. With plain arrays in functions, that size gets lost.

If you have more questions, I am here to help.

C++
This question was asked as part of the Learn C++ Basics course.