Click here to Skip to main content
Click here to Skip to main content

Lambda in C (GCC)

, 2 Jul 2013
Rate this:
Please Sign up or sign in to vote.
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.

// 'i' is not defined
for (;;) {  
  int i = 5;
// '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 (*)())_;});


  ({void _() {
  } (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 would make artificial classes so much more fun to tinker with Frown | :(


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

About the Author

Ghosuwa Wogomon

United States United States
No Biography provided

Comments and Discussions

QuestionBeg to differ PinmemberMike Diack3-Jul-13 4:06 
AnswerRe: Beg to differ PinmemberGhosuwa Wogomon3-Jul-13 9:58 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 2 Jul 2013
Article Copyright 2013 by Ghosuwa Wogomon
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid