Colon within the condition in a 'for' loop | SoloLearn: Learn to code for FREE!


Colon within the condition in a 'for' loop

int x[10] = {1,2,3,4,5,6,7,8,9,10}; for (int y : x){ // What does the colon do? switch (y) { case 1: cout << "A"; case 3: cout << "B"; case 7: cout << "C"; case 8: cout << "D"; } }

7/27/2020 7:33:59 AM


3 Answers

New Answer


This is an enhanced for loop in C++ also called range based for loop and is available in c++ since c++11 It generic form is for(range declaration : range expression) { loop body }, parentheses are optional depending on if the body has single statement or multiple, just like classic for loop. range declaration - name variable of type strored in sequence represented by range expression range expression - the actual sequence See for details


Colon ':' is basically a operator which indicates that the y is inside x and assign the y's value to the elements of array one by one


AteFish, did you mean 'assign the elements of the array to y' instead?