c语⾔中宏定义和常量定义的区别
他们有共同的好处就是“⼀改全改,避免输⼊错误”哪两者有不同之处吗?有的。
主要区别就在于,宏定义是在编译之前进⾏的,⽽const是在编译阶段处理的
宏定义不占⽤内存单元⽽const定义的常量占⽤内存单元
宏定义与const常量有着相同的作⽤-----⽤⼀个符号表⽰数据,但是,有些书上说定义数组常量不能⽤const,经过测试也是可以的,环境是vs2015
常量定义定义数组的长度
const int N=66;
int arr[N];
有的书上说是错误的,但经过我在vs2015上测试是可以的
宏定义定义数组的长度
#define N 66
int arr[N];
带参数的宏定义
格式:
#define 宏名(参数列表)要更换的内容
#define SUM(a,b) a+v
程序代码如下:transform和convert的区别
S=SUM(6,8);
将宏定义中的a和b分别替换成6和8,替换后的代码是:
s=6+8;
#define没有数据类型,只是单纯的替换
#include "stdafx.h"
#include<stdlib.h>
#define add(a,b) (a)>(b)?(a):(b)
int main()
{
printf("%s", add("abc", "bcd"));
system("pause");
return0;
}
#include "stdafx.h"
#include<stdlib.h>
#define add(a,b) (a)>(b)?(a):(b)
int main()
{
printf("%d", add(1+2, 3+4));
system("pause");
return0;
}
这些都是可以的
所以⼀般建议使⽤函数不建议使⽤宏定义
宏定义交换两个数值:
#include<stdio.h>
#include<stdlib.h>
#define swap1(a,b){a=a+b;b=a-b;a=a-b;}
#define swap2(a,b){a=a^b;b=a^b;a=a^b;}
int main(){
int a=5;
int b=6;
printf("Before convert: a=%d;b=%d\n",a,b);
swap1(a,b);
printf("After convert: a=%d;b=%d\n",a,b);
int c=7;
int d=8;
printf("Before convert: c=%d;d=%d\n",c,d); swap2(c,d);
printf("After convert: c=%d;d=%d\n",c,d); }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论