他們有共同的好處就是“一改全改,避免輸入錯誤”哪兩者有不同之處嗎?有的。
主要區別就在於,宏定義是在編譯之前進行的,而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 0; }
#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"); return 0; }
這些都是可以的
所以一般建議使用函數不建議使用宏定義
宏定義交換兩個數值:
#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); }
