Implementing GOLANG's "defer"/C++ destructors in C using macros - how to create a clang label from the concatenation of a title and an identifier?
22:44 09 Mar 2026

I have recently taken a break from regular C++ (hobby) programming in order to try implementing some basic destructor functionality in C (in a way which appears more elegant than simply writing the destructor at the end of the function). I have tried attempting to implement the "defer" keyword found in GO, using C macros. However, this appears more difficult than initially seems, due to being unable to concatenate an identifier with a number generated by a constant and then create a label. This may be impossible due to the way the clang compiler processes code.

Here are my main.c main file:

#include 
#include 
#include "defer.h"

int main(void) {
#define DEFER_ID __COUNTER__
    DF_BEGIN(int, 0);
    void *text = malloc(256);
    if (text == NULL) {
        DF_RETURN(1);
    }
    DF(free(text); printf("Text Freed!\n"));
    printf("Put regular code here\n");
    DF_END();
}

and my defer.h deferred execution file:

#ifndef DEFER_H_
#define DEFER_H_

#include 

struct defer_list {
    uint8_t size;
    void *list[256];
};

#define CAT_(a_, b_) a_##b_
#define CAT(a_, b_) CAT_(a_, b_)
#define DF_BEGIN(return_, value_) return_ return__ = value_; struct defer_list defer_list_ = { .size = 0, .list = {} };
#define DF_END() CAT(defer_, DEFER_ID): if (defer_list_.size != 0) goto *(defer_list_.list[--defer_list_.size]); return return__;
#define DF_RETURN(return_) return__ = return_; goto CAT(defer_, DEFER_ID);

#define DF(funct_) ({ defer_list_.list[defer_list_.size++] = &&CAT(a_, __LINE__); if (0) { CAT(a_, __LINE__): do { funct_; } while (0); goto CAT(defer_, DEFER_ID); }; })

#endif // DEFER_H_
c clang deferred-execution