The meaning of colon in c++

Hello Everyone!!

I am a new learner to C++!

Could I ask what is the purpose of adding the colon in the for loop, since it looks so much different from the for loop I have seen before for(int a; a < 10; a++)

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

Thank you so much!!!

The idea is to loop through each element in the array (or vector, or other iterable).

int eights[] = {8, 16, 24}; 
for (int element : eights) {
    std::cout << element << "\n";
  }

The element variable is each element of the array, moving to the next element at the start of each iteration.
On the first iteration, element would be 8.
On the next iteration, element would be 16.
On the next iteration, element would be 24.

For example:

char letters[] = {'a', 'b', 'c', 'd'};  // array of length 4
for (int i = 0; i < 4; i++) {
   char x = letters[i];
   std::cout << x;
}
std::cout << "\n Print it again with other loop: \n";
// this loop does the same thing, but with less code:
for (char x : letters) {
  std::cout << x;
}

demonstration:

#include <iostream> int main() { int nums[] = {4,5,6}; int length = sizeof(nums) / sizeof(nums[0]); for (int i = 0; i < length; i++) { std::cout << nums[i] << ","; } std::cout << "\n"; for (int x : nums) { std::cout << x << ","; } return 0; }
1 Like

Thank you so much for your explanation!!!