C语言类函数宏和一般函数的区别

本文通过一个具体的示例对比了类函数宏与一般函数在C语言中的使用及效果差异。展示了当宏只进行简单的字符串替换时可能出现的问题,并通过实际运行结果说明了一般函数在处理复杂逻辑时的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类函数宏:function-like-macro 用#define使用参数来定义宏,宏的参数用圆括号括起来,可以使一个参数或者多个参数,然后在使用的过程中这些参数将会被替换。

例如:

#define SQUARE(X) X*X //定义类函数宏
z = SQUARE(3); //使用类函数宏
源代码:

[root@rhel6164 test]# cat test.c
#include <stdio.h>
#define SQUARE(X) X*X
int squ_fun(int);
int main(void)
{
    int x = 0;
    printf("Please input one integer(n), and square(n+1) will be shown via two \
ways(function-like macro and general function). The default is 0.\n");
    scanf("%d", &x);
    printf("Evaluating SQUARE(3) is: %d \n", SQUARE(x+1));
    printf("Evaluating squ_fun(3) is: %d \n", squ_fun(x+1));
    return 0;
}

int squ_fun(int i)
{
    int z = 0;
    z = i * i;
    return z;
}
编译&执行:
[root@rhel6164 test]# gcc test.c
[root@rhel6164 test]# ./a.out
Please input one integer(n), and square(n+1) will be shown via two ways(function-like macro and general function). The default is 0.
3
Evaluating SQUARE(3) is: 7
Evaluating squ_fun(3) is: 16
类函数宏只会做字符串替换(宏定义都只会做字符串替换),替换后为3+1*3+1,结果就是7;而一般函数就会把参数带进函数进行计算后返回结果,这里其实就是(3+1)*(3+1)。

友情链接:可变宏参数个数和可变函数参数个数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值