h4ck3d
h4ck3d

Reputation: 6364

Difference between macro and preprocessor

From what I understand , #define blah 8 is a macro . While , # is the pre-processor directive .

Can we say #include,#if,#ifdef,etc. are also macros , or are they called something else ? Or is it that macro is just a term used for #define statements only?

Please correct me if I am wrong.

Upvotes: 17

Views: 20510

Answers (4)

priwiljay
priwiljay

Reputation: 2743

preprocessor modifies the source file before handing it over the compiler.

Consider preprocessor as a program that runs before compiler.

Preprocessor directives are like commands to the preprocessor program.Some common preprocessor directives in C are

  1. #include <header name> - Instructs the preprocessor to paste the text of the given file to the current file.
  2. #if <value> - Checks whether the value is true if so it will include the code until #endif
  3. #define - Useful for defining a constant and creating a macro

macros are name for some fragment of code.So wherever the name is used it get replaced by the fragment of code by the preprocessor program.

eg:

#define BUFFER_SIZE 100
In your code wherever you use BUFFER_SIZE it gets replaced by 100
int a=BUFFER_SIZE;
a becomes 100 here

There are also many predefined macros in C for example __DATE__,__TIME__ etc.

Upvotes: 2

user529758
user529758

Reputation:

Preporcessor: the program that does the preprocessing (file inclusion, macro expansion, conditional compilation).

Macro: a word defined by the #define preprocessor directive that evaluates to some other expression.

Preprocessor directive: a special #-keyword, recognized by the preprocessor.

Upvotes: 4

qwertz
qwertz

Reputation: 14792

#include, #if, etc. are features of the preprocessor.

#define blah 8

Is a preprocessor directive and declares a new macro named blah.

  • Macros are the result of a #define statement.
  • The preprocessor is a feature of C.

Upvotes: 4

James McNellis
James McNellis

Reputation: 355307

Lines that start with # are preprocessing directives. They are directives that tell the preprocessor to do something.

#include, #if, #ifdef, #ifndef, #else, #elif, #endif, #define, #undef, #line, #error, and #pragma are all preprocessing directives. (A line containing only # is also a preprocessing directive, but it has no effect.)

#define blah 8 is a preprocessing directive, it is not a macro. blah is a macro. This #define preprocessing directive defines the macro named blah as an object-like macro replaced by the token 8.

Upvotes: 39

Related Questions