Recently while I was reading through other’s codes on LeetCode, I encountered a few lines of code that were mysterious to me.

static int fastio = []() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

I knew it was for fast I/O but I couldn’t grasp the idea of how it works. So, as always, I googled it and found a really good answer to my questions. link

I’m rephrasing the answer here just to make sure I understood it well. We put thoses functions that configure fast I/O at the very beginning of the code so things don’t get all tangled up. However, when we submit solution code on LeetCode, we are not allowed to access the main function and we cannot just simply put these functions inside the solution method.

Instead, we can declare a static variable and assigan a result from lambda expression, which is defined as

{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}

The parentheses that come before the function body are for specifying formal paremeters of the function. The parentheses that come after the function body are for the actual arguments that are passed to the lambda function. The brackets are for capture list. The capture list defines the outside variables that are accessible from within the lambda function body. more details here

Therefore, this lambda function, which configure fast I/O, runs before the main function runs. The variable fastio is declared static to make it local to the solution file.