Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Macro With Arguments | Macros
C Preprocessing
セクション 2.  2
single

single

bookMacro With Arguments

メニューを表示するにはスワイプしてください

This simple macro calculates the arithmetic mean of two numbers:

main.c

main.c

copy
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

main.c

copy
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

main.c

copy
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

main.c

copy
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:

タスク

スワイプしてコーディングを開始

  1. Create a functional macro MAX with two arguments a and b;
  2. Specify a ternary operator for comparing two numbers as the body of the macro;
  3. Display the larger number.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  2
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt