Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating labels in macro preprocessing in C

Tags:

c

macros

How to write a macro which calls goto END_ label?

For ex:

#define MY_MACRO() \
//How to define goto END_##function_name label??

my_function()
{
    MY_MACRO();

END_my_function:
   return;
}

The MY_MACRO should simply replace with the line

goto END_my_function;
like image 995
Bharathwaaj Avatar asked Feb 07 '26 04:02

Bharathwaaj


2 Answers

I don't think it can be done. Even though some compilers define __FUNCTION__ or __func__, these are not expanded in macros.

However, note that you don't need a separate label for each function: you can use END for all functions and simply write goto END.

like image 163
lhf Avatar answered Feb 12 '26 04:02

lhf


The preprocessor does not know what function it is in. But you can get close -- you'll have to pass the function name to this macro

#include <stdio.h>

#define GOTO_END(f) goto f ## _end

void foo(void)
{
   printf("At the beginning.\n");

   GOTO_END(foo);

   printf("You shouldn't see this.\n");

  foo_end:
   printf("At the end.\n");
   return;
}

int main()
{
   foo();
}
like image 33
bstpierre Avatar answered Feb 12 '26 04:02

bstpierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!