C语言进阶课程学习记录- 函数与宏分析
- 实验-宏和函数
- 实验-宏的副作用
- 实验-宏的妙用
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
实验-宏和函数
#include <stdio.h>
#define RESET(p, len) \
while( len > 0 ) \
((char*)p)[--len] = 0
void reset(void* p, int len)
{
while( len > 0 )
((char*)p)[--len] = 0;
}
int main()
{
int array[] = {1, 2, 3, 4, 5};
int len = sizeof(array);
int i = 0;
for(i=0; i<5; i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
//reset(array, len);//case1
RESET(array, len);//case2
for(i=0; i<5; i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
return 0;
}
/*
output:
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
array[0] = 0
array[1] = 0
array[2] = 0
array[3] = 0
array[4] = 0
*/
实验-宏的副作用
#include <stdio.h>
#define _ADD_(a, b) a + b
#define _MUL_(a, b) a * b
#define _MIN_(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int i = 1;
int j = 10;
printf("%d\n", _MUL_(_ADD_(1, 2), _ADD_(3, 4)));
printf("%d\n", _MIN_(i++, j));
//printf("%d\n", 1 + 2 * 3 + 4);
//printf("%d\n", ((i++) < (j) ? (i++) : (j)));
return 0;
}
/*
output:
11
2
*/
实验-宏的妙用
#include <stdio.h>
#include <malloc.h>
#define MALLOC(type, x) (type*)malloc(sizeof(type)*x)
#define FREE(p) (free(p), p=NULL)
#define LOG_INT(i) printf("%s = %d\n", #i, i)
#define LOG_CHAR(c) printf("%s = %c\n", #c, c)
#define LOG_FLOAT(f) printf("%s = %f\n", #f, f)
#define LOG_POINTER(p) printf("%s = %p\n", #p, p)
#define LOG_STRING(s) printf("%s = %s\n", #s, s)
#define FOREACH(i, n) while(1) { int i = 0, l = n; for(i=0; i < l; i++)
#define BEGIN {
#define END } break; }
int main()
{
int* pi = MALLOC(int, 5);
char* str = "D.T.Software";
LOG_STRING(str);
LOG_POINTER(pi);
FOREACH(k, 5)
BEGIN
pi[k] = k + 1;
END
FOREACH(n, 5)
BEGIN
int value = pi[n];
LOG_INT(value);
END
FREE(pi);
LOG_POINTER(pi);
return 0;
}
/*
output:
str = D.T.Software
pi = 00702D28
value = 1
value = 2
value = 3
value = 4
value = 5
pi = 00000000
*/
小结
宏和函数并不是竞争对手
宏能够接受任何类型的参数,效率高,易出错
函数的参数必须是固定类型,效率稍低,不易出错
宏可以实现函数不能实现的功能