C语言学习笔记--C语言中的宏定义

1. C 语言中的宏定义

1#define 预处理器处理的单元实体之一(因此,预处理器只是简单的进行替换,并
2#define 定义的宏可以出现在程序的任意位置(包括函数体的内部)
3#define 定义之后的代码都可以使用这个宏

2. 定义宏常量 

1#define 定义的宏常量可以直接使用
2#define 定义的宏常量本质为字面

3. 宏定义表达式

1#define 表达式的使用类似函数调用
2#define 表达式可以比函数更强大
3#define 表达式比函数更容易出错

#include <stdio.h>
#define _SUM_(a, b) (a) + (b)
#define _MIN_(a, b) ((a) < (b) ? (a) : (b))
#define _DIM_(a) sizeof(a)/sizeof(*a)
int main()
{
    int a = 1;
    int b = 2;
    int c[4] = {0};
    int s1 = _SUM_(a, b); //(a)+(b)
    int s2 = _SUM_(a, b) * _SUM_(a, b); //(a)+(b)*(a)+(b)
    int m = _MIN_(a++, b); //((a++)<(b)?(a++):(b))
    int d = _DIM_(c); //sizeof(c)/sizeof(*c);
    printf("s1 = %d\n", s1); // 3
    printf("s2 = %d\n", s2); // 5
    printf("m = %d\n", m); // 2
    printf("d = %d\n", d); // 4
    return 0;
}

4. 宏表达式与函数的对比

1)宏表达式被预处理器处理,编译器不知道宏表达式的存在
2)宏表达式用实参完全替代形参,不进行任何运算

3)宏表达式没有任何的调用开销

4)宏表达式中不能出现递归定义
内置宏

#include <stdio.h>
#include <malloc.h>
#define MALLOC(type, x) (type*)malloc(sizeof(type)*x)
#define FREE(p) (free(p), p=NULL)
#define LOG(s) printf("[%s] {%s:%d} %s \n", __DATE__, __FILE__,__LINE__, s)
#define FOREACH(i, m) for(i=0; i<m; i++)
#define BEGIN {
#define END }
int main()
{
    int x = 0;
    int* p = MALLOC(int, 5); //以 int 类型作为参数!
    LOG("Begin to run main code...");FOREACH(x, 5)
    BEGIN
    p[x] = x;
   END
    FOREACH(x, 5)
    BEGIN
    printf("%d\n", p[x]);
    END
    FREE(p);
    LOG("End");
    return 0;
}

 

参考资料:
www.dt4sw.com
http://www.cnblogs.com/5iedu/category/804081.html

posted @ 2016-09-24 14:30  CrazyDiode  阅读(778)  评论(0编辑  收藏  举报