gpt4 book ai didi

c - 这个C代码怎么会有lambda

转载 作者:太空狗 更新时间:2023-10-29 15:01:52 28 4
gpt4 key购买 nike

这段代码:

#include <stdio.h>

int main()
{
void (^a)(void) = ^ void () { printf("test"); } ;
a();
}

使用 clang -Weverything -pedantic -std=c89(版本 clang-800.0.42.1)在没有警告的情况下编译并打印 test

我找不到任何关于具有 lambda 的标准 C 的信息,而且 gcc 有它自己的 lambda 语法,如果存在标准解决方案,他们这样做会很奇怪。

最佳答案

此行为似乎特定于较新版本的 Clang,并且是 language extension called "blocks" .

Wikipedia article on C "blocks"还提供了支持此声明的信息:

Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+, although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+ and non-Apple systems.

上面的重点是我的。在 Clang's language extension page, under the "Block type" section ,它简要概述了 block 类型是什么:

Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.

GCC 也有类似于 block 的东西,称为词法作用域嵌套函数。但是,在有关 C block 的维基百科文章中也指出了一些关键差异:

Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions. However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.

GCC-style nested functions also require dynamic creation of executable thunks when taking the address of the nested function. [...].

上面的重点是我的。

关于c - 这个C代码怎么会有lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41700729/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com