Like typedef, macro will be heavily used in firmware code, and you will encounter it in almost every firmware interview.
Example
#define FIND(x,a) (void*)&x.a - (void*)&x //return the offset of the member a in the structure x
struct test {
int i;
char c;
};
int main()
{
struct test t;
printf("%d\n", FIND(t,c));
return 0;
}
Note
1) #define FIND( x , a ) (void*) &x.a - (void*) &x //still correct.
2) #define FIND (x,a) (void*)&x.a - (void*)&x //WRONG!!
Macro vs Inline
Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:
1) Inline functions follow all the protocols of type safety enforced on normal functions.
Consider the example below which depicts the disadvantage of the lack of type checking. In this example, the result is always the value passed in as the second argument.
#include "iostream.h"
#define MAX(a, b) ((a < b) ? b : a)
int main( void)
{
cout << "Maximum of 10 and 20 is " << MAX("20", "10") << endl;
return 0;
}
Output:
Maximum of 10 and 20 is 10
Maximum of 10 and 20 is 10
2) Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
3) Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.
3) Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.
沒有留言:
張貼留言