Deciphering cppreference.com

I've been stuck on lambdas for a couple of days now https://www.learncpp.com/cpp-tutorial/introduction-to-lambdas-anonymous-functions/ obviously any idiot can copy code from the tutorials (which I've done many times over now). I'm trying to see if I understand properly to see if I'm able to code directly from https://en.cppreference.com/w/cpp/language/lambda following e.g. 4 from cppreference a most basic inline lambda should be written like so:

[captures] {body}

Cppreference gives no indication the lambda needs to be tied to a variable, function. So from my understanding this should work:

 
[] {std::cout << "test"; }


But it doesn't. My concern isn't the problem itself in this instance, it's my deciphering of cppreference.com; give a man a fish, he'll eat for a day. Teach him how to fish & he'll eat for a lifetime.
Last edited on
"It doesn't work" is not an adequate problem description. Please explain what happens vs. what you expected to happen.
I'm not asking for a solution to this exact problem. My question (a big ask really) is for some guidance on how I'm interpreting cppreference.com incorrectly? I just don't see anything I've interpreted from e.g. 4 wrongly. The below is exactly as per the 4th reference on cppreference.com:

1 - Captures are optional so it's been left out.

2 - The statement has been placed in the body of the lambda, as per cppreference.com.


Now in my mind the compiler should write the lambda exactly where it is. Again I must stress my main concern isn't this individual topic, it's how I'm interpreting this wrongly.
You have to keep in mind that a lambda is a function. Simply declaring it will not make the inner statements run. You’d probably want something more like

1
2
3
4
5
6
7
#include <iostream>

int main() {
  []{
    std::cout << "something" << std::endl;
  }();
}
Thanks highwayman, sure I get it, but this is the thing; where is that stated in cppreference.com.

That's the issue i have at the moment, not being able to use cppreference.com; if I understood that I would be fishing so to speak.
Very top:
Constructs a closure: an unnamed function object....



It is quite small I guess..
Last edited on
Thanks highwayman, that's helped greatly.
Glad to help.
The reason it doesn't work is because you didn't put a semicolon after it. Even if you did put a semicolon after it, it wouldn't do anything unless you call it. It's roughly analogous to doing the following:

1
2
3
4
int main()
{
    73;
}
Last edited on
Topic archived. No new replies allowed.