Advantage of macro over in-line in C++

2019-02-13 16:42发布

We know that in-line are favorable as they are checked by the compiler and same operation ( like ++x ) does not evaluate more than once when passed as an argument as compared to macros.

But in an interview I was asked the specific advantages or the circumstances when a macro is more favorable to inline in C++.

Does anyone know the answer or can give a thought on this question ?

9条回答
叼着烟拽天下
2楼-- · 2019-02-13 17:13

Sometimes you want to extend the language in ways that aren't possible with any other method.

#include <iostream>

#define CHECK(x) if (x); else std::cerr << "CHECK(" #x ") failed!" << std::endl

int main() {
    int x = 053;
    CHECK(x == 42);
    return 0;
}

This prints CHECK(x == 42) failed!.

查看更多
贼婆χ
3楼-- · 2019-02-13 17:13

Inline functions are, as the name indicates, restricted to functional tasks, execution of some code.

Macros have a much broader application they may expand e.g to declarations or replace entire language constructs. Some examples (written for C and C++) that can't be done with functions:

typedef struct POD { double a; unsigned b } POD;
#declare POD_INITIALIZER { 1.0, 37u }

POD myPOD = POD_INITIALIZER;

#define DIFFICULT_CASE(X) case (X)+2 :; case (X)+3
#define EASY_CASE(X) case (X)+4 :; case (X)+5

switch (a) {
   default: ++a; break;
   EASY_CASE('0'): --a; break;
   DIFFICULT_CASE('A'): a = helperfunction(a); break;
}

#define PRINT_VALUE(X)                        \
do {                                          \
 char const* _form = #X " has value 0x%lx\n"; \
 fprintf(stderr, _form, (unsigned long)(X));  \
} while (false)

In the context of C++, Boost has a lot of more examples that are more involved and more useful.

But because with such macros you are in some sort extending the language (not strictly, the preprocessor is part of it) many people dislike macros, particularly in the C++ community, a bit less in the C community.

In any case, if you use such constructs you should always be very clear in what the should achieve, document well, and fight against the temptation to obfuscate your code.

查看更多
女痞
4楼-- · 2019-02-13 17:19
    #include <stdio.h>
    #define sq(x) x*x
    int main()
    {  
        printf("%d", sq(2+1));
        printf("%d", sq(2+5));
        return 0;
    }

The output for this code are 5 and 17. Macros expand textually. Its not like functions.

Explanation for this example:

sq(2+1) = 2+1*2+1 = 2+2+1 = 5

sq(2+5) = 2+5*2+5 = 2+10+5 = 17

查看更多
登录 后发表回答