top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a macro in C/C++? How can we define it?

+7 votes
1,005 views
What is a macro in C/C++? How can we define it?
posted Dec 6, 2013 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote
 
Best answer

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

You may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. However, the preprocessor operator defined (see Defined) can never be defined as a macro, and C++'s named operators (see C++ Named Operators) cannot be macros when you are compiling C++.

answer Dec 8, 2013 by Neeraj Pandey
+2 votes

Macro : It is a preprocessor statement.
No type checking.
It is a direct substitute.
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls. Can define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords

answer Dec 9, 2013 by Giri Prasad
+1 vote

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro as part of preprocessing.

There are two kinds of macros.

  • Object-like macros: resemble data objects when used,
  • function-like macros: resemble function calls

Defining a Macro
You may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. However, the preprocessor operator defined (see Defined) can never be defined as a macro, and C++'s named operators (see C++ Named Operators) cannot be macros when you are compiling C++.

Example

#define BUFSIZE  2000   // BUFSIZE is defined as 2000
#if defined BUFSIZE   // we are checking if BUFSIZE is defined or not 
...
#else
...
#endif
answer Dec 6, 2013 by Kumar Mitrasen
Similar Questions
0 votes
#define MY_STRUCT
typedef struct{ 
...
... 
} my_struct;

Above code is giving me error (MY_STRUCT) is not working as expected, Looks that some silly mistake, please point out as I have wasted many hours?

Sorry for hiding my identity?

...