Click here to Skip to main content
13,297,266 members (59,963 online)
Click here to Skip to main content
Add your own
alternative version


5 bookmarked
Posted 2 Jul 2013

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 :(


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

You may also be interested in...

Comments and Discussions

QuestionBeg to differ Pin
Mike Diack3-Jul-13 5:06
memberMike Diack3-Jul-13 5:06 
AnswerRe: Beg to differ Pin
Ghosuwa Wogomon3-Jul-13 10:58
memberGhosuwa Wogomon3-Jul-13 10: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 2 Jul 2013
Article Copyright 2013 by Ghosuwa Wogomon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid