single
Macro With Arguments
メニューを表示するにはスワイプしてください
This simple macro calculates the arithmetic mean of two numbers:
main.c
12345678#include <stdio.h> #define MEAN(X,Y) ((X)+(Y))/2 int main() { printf("Mean: %d\n", MEAN(1053, 6037)); return 0; }
To make the macro able to handle non-integer numbers, we change the specifier and change the arguments to non-integer numbers:
main.c
123456789#include <stdio.h> #define MEAN(X,Y) ((X)+(Y))/2 int main() { double x = MEAN(1057.3, 6038); printf("Mean: %0.1f\n", x); return 0; }
This flexibility can be both an advantage and a problem.
main.c
12345678#include <stdio.h> #define SUM(a,b) (a + b) int main() { printf("sum: %d\n", SUM(4+5, 2+3)); return 0; }
In this case, the compiler perceives the arguments not as integers 9 and 6, but as the expression 4+5+2+3.
An additional pair of parentheses for the arguments when creating a macro does not solve this problem.
For the next task, let's remember what a ternary operator is:
If the expression a > b is true, the program will return a, if the expression is false, the program will return b.
Why not just use functions?
Speed
Macros work at the preprocessor level, meaning they substitute code directly before compilation. This eliminates the overhead associated with calling functions (saving/restoring registers, jumping by address, etc.).
Using macro:
Using function:
Universality of types
Functions require specifying the types of arguments and return values, while macros simply substitute code, so they can work with any type.
main.c
123456789#include <stdio.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) int main() { int maxInt = MAX(3, 7); // 7 float maxFloat = MAX(3.14, 2.71); // 3.14 return 0; }
Key takeaways:
スワイプしてコーディングを開始
- Create a functional macro
MAXwith two argumentsaandb; - Specify a ternary operator for comparing two numbers as the body of the macro;
- Display the larger number.
解答
フィードバックありがとうございます!
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください