-1
#include <iostream>
using namespace std;
int arr[] = { 1, 2, 3 };

void Show()
{
    for (int val : arr) {
        cout << val;
    }
}

int main()
{
    Show();
    return 0;
}

result will be 123 . i will be very grateful to get explanation of this -int val :arr- specifically what - : - does here ? what is it .

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114

1 Answers1

2

It is called range loop.

int arr[] = { 1, 2, 3 };
for (int val : arr)
   cout << val;

works the same as:

int arr[] = { 1, 2, 3 };
for (int i=0;i<sizeof(arr)/sizeof(int);i++)
{
   int val=arr[i];
   cout << val;
}

But range loop can do far more.

It simply means loop through all members. Keep in mind some classes can have a complicated iterator and a range for runs through an array in a clean way. Also, notice it is a c++11 feature.

Arash
  • 2,114
  • 11
  • 16