0
0
Cprogramming~10 mins

Macro with arguments - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a macro named SQUARE that calculates the square of a number.

C
#define SQUARE([1]) (([1]) * ([1]))

int main() {
    int x = 5;
    int result = SQUARE(x);
    return 0;
}
Drag options to blanks, or click blank then click option'
Anum
Bx
Cval
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put parentheses around the argument in the macro definition.
Using invalid characters or spaces in the macro argument.
2fill in blank
medium

Complete the macro definition to create a macro MAX that returns the maximum of two values a and b.

C
#define MAX(a, b) (([1]) > (b) ? (a) : (b))

int main() {
    int max_val = MAX(3, 7);
    return 0;
}
Drag options to blanks, or click blank then click option'
AMAX
Ba
Cb
Dc
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the arguments in the comparison, which changes the logic.
Forgetting parentheses around macro arguments.
3fill in blank
hard

Fix the error in the macro to correctly compute the cube of a number x.

C
#define CUBE(x) (([1]) * (x) * (x))

int main() {
    int c = CUBE(3);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ax
BCUBE
C3
Dy
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the macro argument.
Hardcoding a number instead of using the argument.
4fill in blank
hard

Fill both blanks to define a macro MIN that returns the minimum of two values x and y.

C
#define MIN([1], [2]) ((([1]) < ([2])) ? ([1]) : ([2]))

int main() {
    int m = MIN(10, 20);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ax
By
Ca
Db
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing argument names or using different names in different parts.
Forgetting parentheses around arguments.
5fill in blank
hard

Fill all three blanks to define a macro SWAP that swaps two variables a and b using a temporary variable temp.

C
#define SWAP([1], [2], [3]) \
    do { \
        int [3] = [1]; \
        [1] = [2]; \
        [2] = [3]; \
    } while(0)

int main() {
    int x = 5, y = 10;
    SWAP(x, y, temp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aa
Bb
Ctemp
Dswap
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name for the temporary variable and one of the variables to swap.
Forgetting the do-while(0) structure for safe macro usage.