Igor_Parfenov's blog

By Igor_Parfenov, history, 17 months ago, In English
Code1

Look at this code. It seems, the expected output is always 1. However, in

  • Codeforces
    • G++20
    • G++17
    • G++14
    • VC++2017
  • in my local Windows G++ 8.1.0
  • in my local Debian G++ 10.2.1

the output is always 0. In Codeforces::Clang++17 & Clang++20 the output is

Clang++
Code2

Now look at this code. Here in all previously mensioned compilers (including Clang++) the output is always 1.

How found
  • Vote: I like it
  • +39
  • Vote: I do not like it

| Write comment?
»
17 months ago, # |
  Vote: I like it +184 Vote: I do not like it

You are actually invoking undefined behavior.

The lambda on the RHS actually doesn't return bool but std::vector<bool>::reference. When the function returns, the vector goes out of scope and the attempt to read the value is UB. If you change the lambda return signature to bool or cast (bool)a[0] it'll work.

»
17 months ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

The following update works fine on all Codeforces Custom Test C++ compilers.

Update

I often use the const auto <lambda_expression_name> = ... syntax to let the compiler infer the return-value type automatically. This works fine, except in some cases when the inferred type should be a reference and when the lambda expression is defined recursively.

»
17 months ago, # |
  Vote: I like it -27 Vote: I do not like it

You should prefer vector<char> to vector<bool>

»
17 months ago, # |
Rev. 2   Vote: I like it -9 Vote: I do not like it

That is why I prefer to explicitly specify the return type of lambda functions.

»
17 months ago, # |
  Vote: I like it 0 Vote: I do not like it

function <bool()> func=[]() -> bool { solves your problem.