+ 7

How the code works?

I've found a code that looks like this... void PrintValue(int value) { cout << "Value = " << value << endl; } void ForEach(const vector<int>& array, void (*func)(int)) { for(int value : array) func(value); } int main() { vector<int> someArray = {5,2,4,3,1}; ForEach(someArray, PrintValue); } Why function PrintValue can be assign on parameter like a variable? does it still a function or it was converted or something like that? And what i didn't understood is for(int value : array). I've never seen loop like this and how it works?

24th Dec 2018, 12:19 AM
ZΛRTHΛИ
ZΛRTHΛИ - avatar
2 Answers
+ 3
The second argument in the ForEach function is a function pointer. It allows you to pass a function as a parameter And that loop is called a foreach loop. I hope you can now look these up and learn some more things about these C++ features. They're powerful and very useful for advanced coding
24th Dec 2018, 4:13 AM
Zeke Williams
Zeke Williams - avatar
+ 4
25th Dec 2018, 3:01 PM
ZΛRTHΛИ
ZΛRTHΛИ - avatar