ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
#define IS_POSITIVE(x) ((x) > 0)
#define IS_NEGATIVE(x) ((x) < 0)
#define IS_ZERO(x) ((x) == 0)
int classify(int n) {
    if (IS_POSITIVE(n)) return 1;
    if (IS_NEGATIVE(n)) return -1;
    return 0;
}
int main(void) {
    printf("%d %d %d", classify(5), classify(-3), classify(0));
}
  1. A. 1 -1 0
  2. B. 1 1 0
  3. C. -1 1 0
  4. D. 1 -1 1

Correct answer: A. 1 -1 0

Each macro expands to a simple, fully-parenthesized boolean test, avoiding any precedence traps. classify(5): 5>0 true, returns 1. classify(-3): -3>0 false, -3<0 true, returns -1. classify(0): neither positive nor negative, falls through to return 0.

More C Programming questions

Exams that ask this topic