Wednesday, 5 December 2012

Worth Read #13

C Preprocessor example2: 
Write the "standard" MIN macro-that is, a macro that takes two arguments and returns the smaller of the two arguments.
#define MIN(A,B) ((A)<= (B) ? (A) : (B))

The purpose of this question is to test the following:
• Basic knowledge of the #define directive as used in macros. This is important because until the inline operator becomes part of standard C, macros are the only portable way of generating inline code. Inline code is often necessary in embedded systems in order to achieve the required performance level
• Knowledge of the ternary conditional operator. This operator exists in C because it allows the compiler to produce more optimal code than an if-then-else sequence. Given that performance is normally an issue in embedded systems, knowledge and use of this construct is important
• Understanding of the need to very carefully parenthesize arguments to macros
• I also use this question to start a discussion on the side effects of macros, for example, what happens when you write code such as:
least = MIN(*p++, b);

No comments:

Post a Comment