Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C
Tip/Trick

Lambda in C (GCC)

Rate me:
Please Sign up or sign in to vote.
2.60/5 (2 votes)
2 Jul 2013CPOL 17.9K   5   2
How to use lambda functions in C

Blocks and Embedded Functions Are Awesome

'Nuff said. I'm sure if you've worked with C, you've found yourself creating variables inside of blocks.

C++
// 'i' is not defined
for (;;) {  
  int i = 5;
  break; 
}  
// 'i' is not defined   

Well, the GCC and a possibly a few other compilers (idk, haven't tested) also feature embedded functions.

int MyFn() {
  int MySub() {
     return 5;
  }
  return MySub(); 
}     

Well, what do you get when you combine block scoping and embedded functions?

int main(int argc, char *argv[]) {
  void (*MySub1)() = ({void _() {
    printf("Hello ");
  } (void (*)())_;});

  MySub1();

  ({void _() {
    printf("World!\n");
  } (void (*)())_;})();

  return 0;
}  

Lambda! Pretty neat huh? The first one is the initialization of a function pointer in place, and the second one is immediate execution. The concept is pretty simple. You just write a normal function. (name doesn't matter, can be 'lambda' or just '_', etc.)

Then, afterwords write a single line with just the name of the function being casted to a pointer. Surround everything in brackets to give it it's own scope, then put parentheses around the brackets to turn it into an expression and voila! Sadly, this doesn't work for initializing structs.

struct {
  void (*sayHello)();
} myclass = {
  ({void _() { 
    printf("Hello World!\n");
  } (void (*)())_;});
}   

The above code will throw an error about braced-group within expressions only being allowed in functions. So sad...it would make artificial classes so much more fun to tinker with :(

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionBeg to differ Pin
Mike Diack3-Jul-13 4:06
Mike Diack3-Jul-13 4:06 
AnswerRe: Beg to differ Pin
Ghosuwa Wogomon3-Jul-13 9:58
Ghosuwa Wogomon3-Jul-13 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.