Macros


1. What is a macro? name some examples of predefined macros?
Ans:
A macro is a named constant, which increases program’s readability.

Some predefined macros:
NULL,
YELLOW,
SEEK_SET,
EOF

2. What is the advantage of macro with arguments, compared to functions with arguments.
Ans:
Faster execution, because as the macro template is replaced with its expansion code at the point of its use, no overhead of transfer of control from & to a function.

Macros with arguments are usually used for small mathematical formulae.
Ex1: #define PRODUCT( p ) p * p
Ex2 : #define AREA( r ) 3.142517 * r * r

3.What is the important point to be noted in macros with arguments?
Ans:
Putting parenthesis in the macro expansion (otherwise the result may not be as expected).
Eg:

#define SQUARE( p ) p * p

int square( int p )
{
return (p * p);
}

main()
{
int a = 3, b = 2, x, y;
clrscr();

x = SQUARE( a + b );

y = square ( a + b);

printf("Result from macros : %d\n", x);          (  11
printf("Result from function : %d", y); (  25

getch();
}

4. What is  # called as?
Ans:
Preprocessor directive

5. What are preprocessor directives?
Ans:
What ever followed after # is called as preprocessor directive.
Eg: #include , #define etc.
These direct the preprocessor program to do a specific task.

6. What are the steps before execution?
Ans:
Editing
(On an editor s/w by a programmer)

Preprocessing
(by preprocessor s/w)

Parsing
(By parser – (syntax checking) s/w)

Compilation
(By Compiler s/w)

Linking
(By Linker s/w)

Loading
(By loader s/w (a part of OS))

Execution
(By CPU)

7. What are the different types of macros?
Ans:
a) Simple macros
b) Macros with argument

8. Why macros are defined in uppercase?
Ans:
Just a convention (easily recognized by the programmer)

9. What are the disadvantages of macros?
Ans:
If we use them instead of function with arguments, then evaluation of arguments doesn't take place.
Type checking is not done, which may lead to incorrect results.