0

While solving Leetcode Problems I have encountered a problem solution (where generally we get access to only the solution class, not the main) where I have found this statement after class declaration & definition. I am acquainted with the inside content like cin.tie sync_with_stdio etc. But what is the auto speedup with [](){//}() is doing. Is it a self-executing function. Any help will be highly appreciated.

   auto speedup=[](){
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        return nullptr;
    }();

Thanks in advance.

mask000
  • 3
  • 1
  • 3
  • 2
    It's a [lambda expression](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) which is called immediately after declaration (hence the final `()`). But why would anyone do such thing instead of just executing these lines in parent scope - I don't know. – Yksisarvinen Apr 06 '20 at 09:47
  • 1
    @Yksisarvinen - it's someone trying to demonstrate they're smarter than other developers, and failing. – Peter Apr 06 '20 at 10:14
  • Understood. Thanks for the help. Because the web Ide doesn't let access to the `main()`. As it gets called immediately after the declaration, so it's getting executed before any lines of main gets executed. – mask000 Apr 06 '20 at 10:19
  • @Yksisarvinen I think it's to do some processing at static initialization time, before main program execution. You can't put any statement that is not a declaration at global scope, so this is actually an elegant way of doing some complex initialization without needing any calls from outside. – Anonymous1847 Apr 08 '20 at 03:54

1 Answers1

1

From the [] to the } is a lambda expression, also known as an anonymous function. It was introduced in C++11. It evaluates to a pointer to a function which takes no arguments and executes the code in the given function body, then returns nullptr.

That statement is calling this lambda function and placing its return value in speedup. Since the lambda expression didn't give an explicit return type, I'm pretty sure the return type, and thus the type of the speedup variable, is nullptr_t.

Anonymous1847
  • 2,518
  • 8
  • 15