-1

In the following code what is the meaning of colon? and where callback function came from?

using void_callback_f = void (*)();
std::vector<void_callback_f> _reload_callbacks;

void Reload() {
    for (const auto& callback : _reload_callbacks) {
        callback();
    }
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 2
    This should be of use: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – eerorika Feb 19 '20 at 05:10
  • 1
    If you meaning the colon in for loop it is kind of foreach loop without counting the index. It is one way to write for loop in c++, javascripts etc. – Ardahan Kisbet Feb 19 '20 at 05:10
  • Ardahan Kisbet : thank you for your answer. – Muhammad Rabieh Feb 19 '20 at 05:28
  • Ardahan Kisbet : what about callback function there is no declaration for it in the code? – Muhammad Rabieh Feb 19 '20 at 05:29
  • 2
    also duplicates: [In for (int val :arr), what does the colon mean?](https://stackoverflow.com/q/47275141/995714), [What does “ for (const auto &s : strs) {} ” mean?](https://stackoverflow.com/q/22225148/995714), [What is “for (x : y)”?](https://stackoverflow.com/q/24946027/995714) – phuclv Feb 19 '20 at 05:40
  • phuclv : thank you for your comments I understand now the problem is the return type in my code was function which confused me a lot. thank you again for your comments. – Muhammad Rabieh Feb 19 '20 at 05:47

1 Answers1

3

The colon in the for loop is an example of Range-based for loop

range_expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and assigned to the variable with the type and name given in range_declaration.

Please check here for more information

Paul
  • 448
  • 1
  • 6
  • 14
  • what about callback function there is no declaration for it in the code? thank you for your answer. – Muhammad Rabieh Feb 19 '20 at 05:26
  • Remy Lebeau : thank you for your answer. – Muhammad Rabieh Feb 19 '20 at 05:48
  • 2
    @MuhammadRabieh yes, it is declared, by the `const auto& callback` in the loop. Did you even read the link Paul gave you? It explains how the syntax of the loop works. The [`auto`](https://en.cppreference.com/w/cpp/language/auto) just means the type of `callback` is deduced by the compiler based on the type of container being looped through. Since a `std::vector` is being looped, the type of `callback` is deduced as `void_callback_f`. On each loop iteration, the next element of the vector gets assigned to `callback` – Remy Lebeau Feb 19 '20 at 05:51
  • Remy Lebeau : thank you very much for your clarification. – Muhammad Rabieh Feb 19 '20 at 06:04