Skip to content

Add Clang Support For Nested Functions In C #169011

@mcmah309

Description

@mcmah309

Clang currently does not support nested functions in C, while gcc does. Nested functions have a variety of uses, but most useful may be allowing the creation of a defer macro that runs code when exiting a scope. This is exactly like defer statements from other languages (e.g. Go, Swift, D, Vala, Nim, Zig) and brings this power and safety to C. Clang should support nested functions in C to enable use cases like this.

e.g.

#include <stdio.h>

#define __DEFER_CAT_IMPL(a, b) a##b

#define __DEFER_CAT(a, b) __DEFER_CAT_IMPL(a, b)

#define __DEFER_UNIQUE_ID(prefix) __DEFER_CAT(prefix, __LINE__)

#define __DEFER_IMPL(cleanup_statement, unique_name)                           \
  auto void unique_name(void* p __attribute__((unused))) {                     \
    cleanup_statement;                                                         \
  }                                                                            \
  char __DEFER_CAT(__defer_var_, unique_name)                                  \
      __attribute__((cleanup(unique_name)))

#define DEFER(cleanup_statement)                                               \
  __DEFER_IMPL(cleanup_statement, __DEFER_UNIQUE_ID(__defer_func_))

int main(void) {
  printf("outer scope start\n");
  {
    printf("inner scope start\n");
    DEFER({
      printf("Defer 1 ran\n");
    });
    DEFER({
      printf("Defer 2 ran\n");
    });
    printf("inner scope end\n");
  }
  printf("outer scope end\n");
}

Output with gcc

outer scope start
inner scope start
inner scope end
Defer 2 ran
Defer 1 ran
outer scope end

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"duplicateResolved as duplicateextension:gnu

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions