Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning is this code block [=,&i]()mutable {}()?

Tags:

c++

lambda

I was taking a c++ test and there was a strange code block below which I didn't understand. Here, i is an int and code is a char:

[=,&i]()mutable
{
  i++;
  code = 'b';
  std::cout << "i:" <<i<<"""code:"<<code <<cout::endl;
}();

I don't know how to interpret this; it doesn't look like a typical C++ code block. I've searched online for information about this but can't find anything else on this sort of code style.

What does this code mean?

like image 872
lzrobbytan Avatar asked Jul 01 '16 17:07

lzrobbytan


People also ask

What is the meaning of CodeBlocks?

In computer programming, a block or code block or block of code is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements.

Is block code real code?

Block coding turns programming into a drag-and-drop process by converting text based code into visual blocks. Each block contains real code and when they're combined together, they create animations and games.


1 Answers

This is a lambda function, a feature added to the language in 2011.

  • The = means that copies of variables from the outside are available inside.
  • The &i means that, despite the above, i in particular is actually available by reference.
  • The mutable keyword allows the code copy to be modified inside the function body.
  • The trailing () "runs" the function immediately after it's declared.

As written, I can't see any particular reason to use a lambda for this. It looks like someone has succeeded at their goal: to confuse you.

like image 194
Lightness Races in Orbit Avatar answered Oct 02 '22 00:10

Lightness Races in Orbit