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

C and C++ Interview Questions

20. Is it better to use a macro or a function?

Ans:
The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs. A function is more suited for this type of situation. Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.

Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.

Ex - 1: What will be printed as the result of the operation below:
int x;
int modifyvalue()
{
    return(x+=10);
}
int changevalue(int x)
{
    return(x+=1);
}
void main()
{
    int x=10;
    x++;
    changevalue(x);
    x++;
    modifyvalue();
    printf("First output:%dn",x);
    x++;
    changevalue(x);
    printf("Second output:%dn",x);
    modifyvalue();
    printf("Third output:%dn",x);
}
Ans: 12 , 13 , 13


SLogix Student Projects
bottom