What does the : operator do?

Hi I have a simple question about the : operator. I do not remember using it and it is giving me some trouble understanding a simple project.

https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-code-challenge-functions/exercises/cpp-functions-cc-first-three-multiples

in int main
int main() {

for (int element : first_three_multiples(8)) {
std::cout << element << “\n”;
}

}
what does the : operator do?

It is called a range based for loop but you can essentially think of the colon as “in”. When used in a for loop it’s saying “for each element in the vector first_three_multiples(8) do something”. So the loop is creating an integer called element, then assigning it the value of the first element of the vector and this is then printed. It then takes the second element of the vector, and assigns this value to element. It continues like this until the end of the vector.

This exists to give a much easier way of writing a for loop to go over a specific range. If you didn’t have access to this operator, you would need to do a full for loop, like so:

  std::vector<int> multiples_of_eight = first_three_multiples(8);
  for (int i = 0; i < multiples_of_eight.size(); i++) {
    std::cout << multiples_of_eight[i] << "\n";
  }

This works perfectly fine and does the same job, but it’s clear there’s more coding and it could be a bit harder to identify problems in a large code set. Plus there’s the problem of defining a new vector in the namespace which could cause an issue. You don’t need to define the vector, but then the code becomes even more messy:

  for (int i = 0; i < first_three_multiples(8).size(); i++) {
    std::cout << first_three_multiples(8)[i] << "\n";
  }

Therefore having the : operator makes the code cleaner and more readable, and is incredibly useful when looping through vectors.

2 Likes