【学习笔记】C 语言中的 lambda

lambdas-in-c

今天,我了解到 gcc C 至少从 3.0.4 版本开始支持 lambda 函数。我希望我早点知道。

在最近的 海牙 GNU 黑客会议上,Paolo Carlini 做了 关于 C++0x 和 gcc 的演讲。他提到的一个新功能是 C++ 对 lambda 函数的支持。我想,如果 g++ 有它们,将它们引入 gcc 应该不会太难。我问 Paolo,他说他听说过一个项目正在研究这个问题。酷。

今天,我去寻找在 gcc 中从事 lambda 函数工作的人。我没有找到他们。相反,我发现了一些更酷的东西:GNU C 的复合语句和宏足以获得 95% 的 lambda。如下:

#include <stdlib.h>
#include <stdio.h>


/* Create a lambda function.  Note: unlike lambdas in functional
   languages, this lambda does not capture the containing
   environment.  Thus, if you access the enclosing environment, you
   must ensure that the lifetime of this lambda is bound by the
   lifetime of the enclosing environment (i.e., until the enclosing
   function returns).  This means that if you access local
   variables, bad things will happen.  If you don't access local
   variables, you're fine.  */
#define lambda(l_ret_type, l_arguments, l_body)         \
  ({                                                    \
    l_ret_type l_anonymous_functions_name l_arguments   \
      l_body                                            \
    &l_anonymous_functions_name;                        \
  })

int
main (int argc, char *argv[])
{
  int array[] = { 4, 3, 1, 2, 5 };

  void dump (void)
  {
    int i;
    for (i = 0; i < sizeof (array) / sizeof (array[0]); i ++)
      printf ("%d ", array[i]);
    printf ("\n");
  }

  printf ("Initial: ");
  dump ();

  /* Ensure that the lambda is a nested function and thus requires a
     trampoline.  */
  int comparison = 0;

  qsort (array, sizeof (array) / sizeof (array[0]), sizeof (array[0]),
         lambda (int, (const void *a, const void *b),
                 {
                   dump ();
                   printf ("Comparison %d: %d and %d\n",
                           ++ comparison, *(const int *) a, *(const int *) b);
                   return *(const int *) a - *(const int *) b;
                 }));

  printf ("Sorted: ");
  dump ();

  return 0;
}

Output:

$ gcc -Wall a.c -o a && ./a
Initial: 4 3 1 2 5 
4 3 1 2 5 
Comparison 1: 4 and 3
3 4 1 2 5 
Comparison 2: 2 and 5
3 4 1 2 5 
Comparison 3: 1 and 2
3 4 1 2 5 
Comparison 4: 3 and 1
3 4 1 2 5 
Comparison 5: 3 and 2
3 4 1 2 5 
Comparison 6: 3 and 5
3 4 1 2 5 
Comparison 7: 4 and 5
Sorted: 1 2 3 4 5 

太棒了。而且,它只使用 gcc 支持了十多年的功能。太棒了

剩下的问题是:这种行为是可靠的还是基于实现上的特殊性。?我通过电子邮件发送了 gcc 帮助列表。Ian Lance Taylor 回答说行为尚未定义,但到目前为止是稳定的。他的建议是打开一个错误并请求明确允许这种可取的(!!!)行为。


【参考资料】

本文章翻译自

lambdas-in-c (walfield.org)


本文链接:https://blog.csdn.net/u012028275/article/details/134354482

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值