Mayank
Mayank

Reputation: 2210

Macro having structure with parentheses

I just found somewhere a code like :

#include"stdio.h"

typedef struct st
{
  int num;
  char c;
  int abc;
} Str, *pStr;

#define MyStr(Dcn) Str(Dcn)

int main()
{
  Str Str1;
  MyStr(Dcn);
  return 0;
}

Please tell what the #define line means here? As it is not giving any compilation problem. So if I use #define something to a "structure with parentheses" then what happens?

Here Dcn can be anything not with quotes. When I used a number instead it showed compilation error.

Upvotes: 0

Views: 79

Answers (2)

unwind
unwind

Reputation: 399871

It's a function-like macro, it's expanded to the right-hand side with the arguments replaced.

A classical example is this, to compute max of two values:

#define MAX(a, b)    ((a) > (b) ? a : b)

You can use it like this:

int hello = 12, there = 47;
int what = MAX(hello, there);

The second line will expand to:

int what = ((12) > (47) ? 12 : 47);

In other words, what will be 47. Note that this macro evaluates its arguments more than once, which can be harmful if there are side-effects.

As of C99, you can also do variadic preprocessor macros.

The code you're showing will expand to:

Str Str1;
Str(Dcn);  /* This is the macro-expansion. */

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

This defines an alias for Str. It is equivalent to

int main()
{
    Str Str1;
    Str(Dcn);
    return 0;
}

Which simply declares a variable Dcn of type Str.

Upvotes: 4

Related Questions