ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define CLAMP(x, lo, hi) MIN(MAX(x, lo), hi)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main(void) {
    printf("%d", CLAMP(15, 0, 10));
}
  1. A. 15
  2. B. 0
  3. C. 10
  4. D. Compile-time error: MAX is used in CLAMP before being defined

Correct answer: C. 10

Macros are expanded only at the point of USE (in the translation unit, after the preprocessor has seen the whole file's relevant #define directives before compilation proper begins), not strictly in textual declaration order for nested macro calls within a single file, as long as MAX is defined somewhere before CLAMP is actually invoked in the code being compiled. CLAMP(15,0,10) computes MAX(15,0)=15, then MIN(15,10)=10.

More C Programming questions

Exams that ask this topic