Challenge - 5 Problems
Macro Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of macro with arguments
What is the output of this C program?
C
#include <stdio.h> #define SQUARE(x) x * x int main() { int a = 3; int result = SQUARE(a + 1); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Remember how macros expand without parentheses around arguments.
✗ Incorrect
The macro expands to a + 1 * a + 1 which is 3 + 1 * 3 + 1 = 3 + 3 + 1 = 7, but operator precedence causes multiplication before addition, so it is 3 + (1 * 3) + 1 = 7. However, the macro is SQUARE(x) x * x, so SQUARE(a + 1) expands to a + 1 * a + 1 which is 3 + 1 * 3 + 1 = 7. The output is 7, so option A is correct.
❓ Predict Output
intermediate2:00remaining
Correct macro usage with parentheses
What is the output of this C program?
C
#include <stdio.h> #define SQUARE(x) ((x) * (x)) int main() { int a = 3; int result = SQUARE(a + 1); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Parentheses in macros help control operator precedence.
✗ Incorrect
The macro expands to ((a + 1) * (a + 1)) which is (4 * 4) = 16.
🔧 Debug
advanced2:00remaining
Identify the error in macro with arguments
What error does this code produce when compiled?
C
#include <stdio.h> #define MAX(a, b) a > b ? a : b int main() { int x = 5, y = 10; int max_val = MAX(x, y); printf("%d\n", max_val); return 0; }
Attempts:
2 left
💡 Hint
Check how the macro expands and operator precedence.
✗ Incorrect
The macro expands to x > y ? x : y which is 5 > 10 ? 5 : 10, so it prints 10. No syntax error occurs here.
❓ Predict Output
advanced2:00remaining
Macro side effects with arguments
What is the output of this C program?
C
#include <stdio.h> #define INCREMENT(x) (x + 1) int main() { int a = 5; int result = INCREMENT(a++) * 2; printf("%d %d\n", result, a); return 0; }
Attempts:
2 left
💡 Hint
Macros can cause unexpected side effects when arguments have increments.
✗ Incorrect
The macro expands to (a++ + 1) * 2. a++ (post-increment) evaluates to the current value 5, 5 + 1 = 6, then 6 * 2 = 12, and a is incremented to 6 afterward. Prints '12 6'. The argument is evaluated only once, so no undefined behavior.
🧠 Conceptual
expert2:00remaining
Why use parentheses in macro arguments?
Which option best explains why parentheses are important around macro arguments and the entire macro body?
Attempts:
2 left
💡 Hint
Think about how expressions combine when macros are expanded.
✗ Incorrect
Parentheses ensure that when the macro is expanded, the expression behaves as intended by controlling the order of operations and grouping the entire expression.