c语言中宏定义和常量定义的区别

时间:2023-03-08 21:07:25

  他们有共同的好处就是“一改全改,避免输入错误”哪两者有不同之处吗?有的。

  主要区别就在于,宏定义是在编译之前进行的,而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

程序代码如下:

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");
return ;
}
#include "stdafx.h"
#include<stdlib.h>
#define add(a,b) (a)>(b)?(a):(b)
int main()
{
printf("%d", add(+, +));
system("pause");
return ;
}

这些都是可以的

所以一般建议使用函数不建议使用宏定义

宏定义交换两个数值:

#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=;
int b=;
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=;
int d=;
printf("Before convert: c=%d;d=%d\n",c,d);
swap2(c,d);
printf("After convert: c=%d;d=%d\n",c,d);
}