随笔 - 6  文章 - 0  评论 - 0  阅读 - 213

C++宏和函数的比较

在上一篇随笔中,我提到宏和函数是很相似的,那么在这篇中我会通过实例来体会宏和函数的异同。
实例:分别用函数和带参的宏,从三个数中找出最大的数
代码:

点击查看代码
#include<bits/stdc++.h>
using namespace std;
#define Com(a,b,c) {printf("%.3f\n",max(a,max(b,c)));}
void compare(float a,float b,float c);
int main()
{
    float a,b,c;
    cin>>a>>b>>c;
    compare(a,b,c);
    Com(a,b,c);
    return 0;
}
void compare(float a,float b,float c){
    cout<<fixed<<setprecision(3)<<max(a,max(b,c))<<endl;
}
在代码中我们能更直观体会到函数和宏的相似性。同时我们注意到,尽管max(a,b)函数只能比较两个数的大小,但可通过套用变形为max(a,max(b,c))从而达到比较三个数的效果。
posted on   Station  阅读(4)  评论(0编辑  收藏  举报
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示