Is range-based loop identical to for loop?

The code below works correctly. It checks for the letter 'd'. Iterations stop if the word has a 'd' in it.

My question is, does this mean that behind the range-based syntax is actually a for loop? Like the range-based syntax is an alias for it? Or are there differences in the range-based loop. For instance, could I put more complicated code in the block, like function calls?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main()
{
	std::string word = "radar";
	bool found = false;
	int ctr = 0;
	for (char c : word)
	{
		++ctr;
		if (c == 'd')
		{
			found = true;
			break;
		}
	}

	std::cout << ctr << " iterations. Letter d ";
	if (found) 
	{
		std::cout << "was";
	}
	else
	{
		std::cout << "wasn't";
	}
	std::cout << " found\n";

       return 0;
}
Last edited on
its a for loop, note the for in the front :) You can do anything in the loop body that you can normally do in any other loop body.

what it really is, is pointer/iterator masked syntax sugar. Its hiding the details in the syntax but effectively its using a pointer to each item and handing it to you (as a copy or a reference).

much like function parameters, you usually want a constant reference (for anything larger than an integer) when it does not change (in your example c does not change) and a non-const reference if it does change (eg if you said c= value; in your code). Without the reference, it makes a copy of the data, which can be rather slow if the data is an object.
Last edited on
Yes.

Executes a for loop over a range.

Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
https://en.cppreference.com/w/cpp/language/range-for


Note that in the range-based loop, the end of range sentinel is evaluated only once, before the synthesised for loop.

> For instance, could I put more complicated code in the block, like function calls?

Yes, you could; as long as the code does not modify end of range.

We use the range-for-loop for simple loops over all the elements of a sequence looking at one element at a time. More complicated loops, such as looking at every third element of a vector, looking at only the second half of a vector, or comparing elements of two vectors, are usually better done using the more complicated and more general traditional for-statement
Stroustrup in 'Programming: Principles and Practice Using C++'
Last edited on
Thanks for the details, I don't pay enough attention to them.
Topic archived. No new replies allowed.