0
0
Cprogramming~5 mins

Macro with arguments - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a macro with arguments in C?
A macro with arguments is a preprocessor directive that defines a reusable code snippet which can take inputs (arguments) and replace them in the code before compilation.
Click to reveal answer
beginner
How do you define a macro with two arguments to add them in C?
#define ADD(x, y) ((x) + (y)) This macro takes two arguments and returns their sum.
Click to reveal answer
intermediate
Why should you use parentheses around macro arguments and the whole macro body?
Parentheses ensure the correct order of operations and prevent unexpected results when the macro is used with complex expressions.
Click to reveal answer
intermediate
What happens if you forget to put parentheses around macro arguments?
The macro may produce wrong results due to operator precedence issues, for example, ADD(2, 3) * 4 could be expanded incorrectly.
Click to reveal answer
beginner
Give an example of a macro with arguments that calculates the maximum of two values.
#define MAX(a, b) ((a) > (b) ? (a) : (b)) This macro returns the larger of two values.
Click to reveal answer
What does this macro do? #define SQUARE(x) ((x) * (x))
ACalculates the square of x
BCalculates the square root of x
CMultiplies x by 2
DAdds x to itself
Why is it important to put parentheses around macro arguments?
ATo avoid syntax errors
BTo make the macro faster
CTo ensure correct order of operations
DTo allow macros to take multiple arguments
What will be the output of this code? #define ADD(x, y) x + y int result = ADD(2, 3) * 4;
A20
BUndefined behavior
CIncorrect code, will not compile
D14
How do you define a macro with three arguments?
A#define MACRO(a, b, c) ...
B#define MACRO(a b c) ...
C#define MACRO[a, b, c] ...
D#define MACRO{a, b, c} ...
Which of these is a correct macro to find the minimum of two numbers?
A#define MIN(a, b) (a < b ? a : b)
B#define MIN(a, b) ((a) < (b) ? (a) : (b))
C#define MIN(a, b) a < b ? a : b
D#define MIN(a, b) a < b ? (a) : (b)
Explain how to write a macro with arguments in C and why parentheses are important.
Think about how the preprocessor replaces code and how operator precedence can affect results.
You got /4 concepts.
    Describe a real-life example where a macro with arguments can simplify your C code.
    Consider simple math operations or comparisons you do often.
    You got /4 concepts.