Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of this C++ macro?

I can't figure out what this macro means:

#define DECLARE_HANDLE(n) typedef struct n##__{int i;}*n

DECLARE_HANDLE(HWND);

I have learned from the C program that:

"##" means connect the parameter.

so the macro equals:

typedef struct HWND__{int i;}*HWND

Is this right?

If it is right, what is the meaning of that sentence?

==================

Code from a game Bombermaaan (for Windows and Linux),
link http://sourceforge.net/p/bombermaaan/code/HEAD/tree/trunk/src/Bombermaaan/winreplace.h,
line No 90.

like image 433
puwei219 Avatar asked May 21 '13 11:05

puwei219


People also ask

What is macro in C with example?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. Here, when we use c in our program, it is replaced with 299792458 .

What are C macros used for?

The Concept of C Macros Macros are generally used to define constant values that are being used repeatedly in program. Macros can even accept arguments and such macros are known as function-like macros. It can be useful if tokens are concatenated into code to simplify some complex declarations.

How do you call a macro in C?

To invoke a macro that takes arguments, you write the name of the macro followed by a list of actual arguments in parentheses, separated by commas. The invocation of the macro need not be restricted to a single logical line—it can cross as many lines in the source file as you wish.

What do you mean by macros?

Macros are used to make a sequence of computing instructions available to the programmer as a single program statement, making the programming task less tedious and less error-prone. (Thus, they are called "macros" because a "big" block of code can be expanded from a "small" sequence of characters.)


2 Answers

Your assumption is correct.

You can check this with the following simple test code.

DECLARE_HANDLE(HWND);
struct HWND__ s;
HWND p = (HWND) malloc(sizeof(struct HWND__));
s.i = 20;
p->i = 100;
cout << "i valueis " << s.i<<" and " << p->i <<endl;
like image 147
Whoami Avatar answered Oct 06 '22 08:10

Whoami


DECLARE_HANDLE(HWND); indeed expands to

typedef struct HWND__{int i;}*HWND;

Now, you're asking what it means? Just split the typedef into two steps:

struct HWND__
{
    int i;
};

typedef HWND__* HWND;  // C++ only; for both C++ and C: typedef struct HWND__* HWND;

Thus, it defines a struct HWND__ containing an int (named i) and declares a type alias HWND as pointer to HWND__.

like image 23
gx_ Avatar answered Oct 06 '22 07:10

gx_