0

I have been seeing code like this in submissions at leetcode.com and I don't understand it. My unfamiliarity with the syntax has made it hard to search for an explanation.

static const int _ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}()

I gather that the I/O calls are an effort to increase execution speed. What I am not grasping is the syntax- is this a function definition, or a lambda expression? How is this code ever executed?

  • It's a _Lambda expression_ https://en.cppreference.com/w/cpp/language/lambda the last `()` is the call to execute it – Richard Critten Jun 03 '21 at 17:11
  • Does this answer your question? [What is a lambda expression in C++11?](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – Richard Critten Jun 03 '21 at 17:14
  • That's a very good link I'll be studying. What's missing for me is the reminder that this code will have to be executed to initialize the static const int variable. – efjellanger Jun 03 '21 at 17:35
  • "_...All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function ..."_ https://en.cppreference.com/w/cpp/language/initialization#Non-local_variables – Richard Critten Jun 03 '21 at 17:41

1 Answers1

1

This is lambda syntax, so what they're doing is creating a c++ lambda which performs the code above and evaluates it, then stores the result as a static const int. More information here: https://en.cppreference.com/w/cpp/language/lambda

My best guess is that this function will be evaluated first before main is called as static const values are initialized prior to starting the program. It seems like a hacky version of a state initializer for stdio.

Guy Marino
  • 429
  • 3
  • 6
  • This makes perfect sense, thanks! I wonder why they've all chosen to use the underscore for the variable name. – efjellanger Jun 03 '21 at 17:34
  • It's traditionally used in C/Python to signify that the variable isn't important or is never used. Hope this helps! – Guy Marino Jun 03 '21 at 17:35