0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

マクロ定義関数

Last updated at Posted at 2025-02-18

以下のコードを実行すると、エラーが出る。「8行目で')'が必要です」とのこと。

マクロていき関数
#include <stdio.h>
#define sum(x, y) (x + y);

int main(void)
{
   int a = 10;
   int b = 20;
   printf("合計は%d", sum(a, b));

   return 0;
}

2行目の#define sum(x, y) (x + y);末尾のセミコロンが原因。うっかり打ってしまいがち。
マクロ関数は、呼ばれた場所で、定義されたとおりに丸ごと展開される。行末にセミコロンがあると、それもろとも展開されてしまう。
このコードでは、8行目がprintf("合計は%d", (a + b););となり、printf関数の閉じカッコが見当たらないといわれる。

仮引数や返却値の型をいちいち設定しなくてもよくなったり、実行効率が上がったりというメリットがある一方で、インクリメントの挙動を見落としたり、使い方によっては展開式が煩雑になったりで、マクロて関数も一長一短…ということらしい。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?