Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor: #define a macro that can be called without parentheses

I was wondering if it is possible to write a macro which behaves like this:

void Func(int x)
{
    printf("%d",x);
}

#define func Func x //or something

int main()
{
    func 10; //<---- remove parenthesis
}

In this case, func will point to the real function Func, and 10 will be its argument without the parenthesis.

I'm trying to achieve something similar to the new operator in C++ but in C.

Example:

class Base* b = new(Base);

In this case, class is a macro for struct, new is a function which takes a function pointer, and Base is a function which allocates memory for struct Base.

I would like to rewrite the code to something like this:

class Base* b = new Base;

Which will be possible if I can come up with a macro :)

like image 819
Mamma Avatar asked Nov 06 '15 09:11

Mamma


2 Answers

Funny enough you may get away with just defining new away (#define new) and defining a token for each constructor-like function which produces a real function call with brackets, like #define BASE Base().

That should make the following code legal C:

#define new
#define class struct
#define BASE Base()

// forward declaration
class Base;
extern class Base *Base();

void f()
{
    class Base* b = new BASE;
}
like image 51
Peter - Reinstate Monica Avatar answered Sep 21 '22 07:09

Peter - Reinstate Monica


I don't think you can do what you want. If you have a macro with a parameter, such as #define func(x) Func(x), then you need to call it as you would call a function:

#define func(x) Func(x)
func(x) // Will be replaced by Func(x) during pre-processing

If you have a macro without parameter, then the value is simply replaced during pre-processing:

#define MY_VAL 110
func(MY_VAL) // Will be replaced by Func (110) during pre-processing

It is easy enough to remove the first bracket...

#define func Func(
func 10);

... is perfectly valid, but quite odd. I don't think there is a way to remove the closing bracket, unfortunately.

As Joachim Pileborg pointed out in his comments, I don't see a good reason to do that in a real C program.

like image 37
Holt Avatar answered Sep 24 '22 07:09

Holt