Reputation:
On the definition of the structure below, there is a line with a macro definition (#define
). What does that line do exactly? I understand it makes an alias to the first entry of the array h_addr_list
, but it still looks weird to me. Is h_addr
a member of the struct hostent
? Is this definition only within the scope of the struct?
struct hostent
{
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses from name server */
#define h_addr h_addr_list[0] /* address, for backward compatiblity */
};
Upvotes: 13
Views: 10181
Reputation: 206699
The macro definition is not scoped at all, it would work the same way if it was defined outside that struct.
It allows old code to continue using hr.h_addr
rather than having to be changed to he.h_addr_list[0]
(assuming he
is a struct hostent
).
To clarify, h_addr
is not a field of struct hostent
. That define is processed by the pre-processor, the actual compiler sees an empty line where the #define
is.
But if a piece of code is written as he.h_addr
, the pre-processor will modify it and replace it with he.h_addr_list[0]
. That is what the actual compiler will see.
Pre-processor macros are never scoped: the compiler proper doesn't even see them - it only sees the result of the substitutions, and the pre-processor ignores (is not aware of) scoping entirely.
Upvotes: 23
Reputation: 23699
Once defined, a macro identifier remains visible independently of the C scoping rules. Its scope begins at its definition, until the end of the translation unit or a corresponding #undef
directive.
Here, the definition inside the structure is just for readibility; you can also define your macro after your structure for example:
struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
};
#define h_addr h_addr_list[0]
It isn't a field at all; it allows the user to write s.h_addr
instead of s.h_addr_list[0]
.
Upvotes: 6
Reputation: 97948
Macro definitions are not scoped so this macro is visible within compilation units that see this definition and until an undef h_addr
.
Upvotes: 0