Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Lambda in C (GCC)

2.60/5 (2 votes)
2 Jul 2013CPOL 18.7K  
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)