In the example below, the functional object "rev" is defined in terms of itself. How is this possible?

This example ( void function f(string& s1, string& s2)) was taken from page 297/298 of version 4 of the new TCPL book B. Stroustup.

#include <iostream>
#include <functional>
#include <string>
#include <algorithm>

void f(std::string& s1, std::string& s2)
{
    std::function<void(char* b, char* e)> rev =
                [&](char* b, char* e) { if (1<e-b) { std::swap(*b,*--e); rev(++b,e); } };
    rev(&s1[0],&s1[0]+s1.size());
    rev(&s2[0],&s2[0]+s2.size());
}

int main()
{
    std::string s1("Hello");
    std::string s2("World");
    f(s1, s2);
    std::cout << s1 << " " << s2 << '\n';
}

The code compiles and outputs the correct results, i.e. function fchanges characters of input lines. Program output:

olleH dlroW

I can understand the semantics of the expression below. My problem is to accept its syntax, since a variable is revdefined in terms of itself.

std::function<void(char* b, char* e)> rev =
                    [&](char* b, char* e) { if (1<e-b) { std::swap(*b,*--e); rev(++b,e); } 
+3
source share
2 answers

(From comments under question)

: rev rev:

                                   // vvv Point of declaration
std::function<void(char* b, char* e)> rev =
    [&](char* b, char* e) { if (1<e-b) { std::swap(*b,*--e); rev(++b,e); }

( , ), rev ( ) .

, :

rev ( ), :

  • ( )
  • jmp ( )

... , ( ).

, , . ,

, " ", .

+5

[&]. rev .

+6

All Articles