© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

1. What is a macro, and how do you use it?

Ans:
A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement. 
Here is an example of a macro:

Macros can also utilize special operators such as the stringizing operator (#) and the concatenation operator (##).The stringizing operator can be used to convert macro parameters to quoted strings, as in the following example:
#define DEBUG_VALUE(v) printf(#v “ is equal to %d.n”, v)
In your program, you can check the value of a variable by invoking the DEBUG_VALUE macro:
...
int x = 20;
DEBUG_VALUE(x);
... The preceding code prints “x is equal to 20.” on-screen. This example shows that the stringizing operator used with macros can be a very handy debugging tool.

Ex - 1:  What is the output?
#define prod(a,b) a*b
main()
{
            int x=3,y=4;
            printf("%d",prod(x+2,y-1));
}

Ans:
10
Explanation:
            The macro expands and evaluates to as:
            x+2*y-1 => x+(2*y)-1 => 10

Ex - 2:  What is the output?
#ifdef something
int some=0;
#endif
 
main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}
 
Ans:
Compiler error : undefined symbol some

Explanation:

This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration int some = 0; effectively removed from the source code.


SLogix Student Projects
bottom