C预处理和宏



预处理,宏,常量,变量
1.预处理
.预处理常量
1.1__FILE__显示源文件完整路径和名称
代码如
prf("the ocde in the file %s\n",__FILE__);
1.2__LINE__显示源文件当前行号
代码如
prf("the ocde in the line %d\n",__LINE__);
1.3__DATE__,__TIME__显示编译时日期和时间
代码如
prf("the last compiled %s %s\n",__DATE__,__TIME__);
1.4__STDC__判断是否为标准ANSI C编译器
#def __STDC__
prf("this is a ANSI complier\n");
#
prf("this isn't a ANSI complier\n");
#end
1.5__cplusplus判断是否为C源码
代码如
#def __cplusplus
prf("Using c\n");
#
prf("using C\n");
#end
1.6# <filename.h>和# "filename.h"差别
# <filename.h>编译器会在当前系统所有系统路径找这个头文件
# "filename.h"编译器只会在当前文件夹找这个头文件
完整代码演示
//per_process.c
# <stdio.h>
per_process{
prf("the ocde in the file %s\n",__FILE__);
prf("the ocde in the line %d\n",__LINE__);
prf("the last compiled %s %s\n",__DATE__,__TIME__);

#def _MSC_VER
prf("using micrsoft complier");
#end

#def _BORLANDC
prf("using borland complier");
#end

#def __STDC__
prf("this is a ANSI complier\n");
#
prf("this isn't a ANSI complier\n");
#end

#def __cplusplus
prf("Using c\n");
#
prf("using C\n");
#end
}
{
per_process;
}


2.宏
(C宏相当于C模板功能)
宏和比较
如果要追求运行速度,就选择用宏来实现
如果不在乎大小,而是追求完整和方便维护,请选择用来实现

2.1定义和取消宏
定义宏名:# 宏名 宏表达式
代码
# _toupper(c) ((((c)>='a')&&((c)<='z')) ? (c) - 'a' +'A':c)
# SUM(x,y)((x)+(y))
# MUL(x,y)((x)*(y))
# MIN(x,y)((x)<(y)?(x):(y))
# MAX(x,y)((x)>(y)?(x):(y))

取消宏名:#undef 宏名
#undef _toupper(c)
#undef SUM(x,y)
#undef MUL(x,y)

2.2判断相关符号是否被定义
代码格式
#ndef/def [符号名]
代码行...
#end
(#ndef是没有定义def是已经定义)
代码例子
#ndef SUM(x,y)
# SUM(x,y)((x)+(y))
prf("ONlY IS A TEST,SUM(3,5)=%d\n",SUM(3,5));
#end

2.3对宏进行-条件处理
#def symbol
//statements...
#
//other statements...
#end
或者
#ndef symbol
//statements...
#
//other statements...
#end
代码例子1
#ndef LIBTYPE
# "mylib1.h"
#
# "mylib2.h"
#end
代码例子1
#def ADDONCE
# "mylib1.h"
#
# "mylib2.h"
#end
2.4在宏中如何使用
宏中每个变量都必须要使用把它们包围起来,这是为了支持表达式计算
否则编译器会编译我们意想不到结果
例如:
# SUM(x,y)((x)+(y))
# MIN(x,y)((x)<(y)?(x):(y))
# CUBE(x)((x)*(x)*(x))

完整代码演示
//demo.c
#def __cplusplus
# <iostream.h>
#
# <stdio.h>
#end

demo{
#ndef _toupper(c)
# _toupper(c) ((((c)>='a')&&((c)<='z')) ? (c) - 'a' +'A':c)
prf("_toupper('b')=%c\n",_toupper('b'));
#
#undef _toupper(c)
#end

# SUM(x,y)((x)+(y))
# MUL(x,y)((x)*(y))
# MIN(x,y)((x)<(y)?(x):(y))
# MAX(x,y)((x)>(y)?(x):(y))
# SQUARE(x)((x)*(x))
# CUBE(x)((x)*(x)*(x))

prf("SUM(3,5)=%d\n",SUM(3,5));
prf("MUL(3,4)=%d\n",MUL(3,4));
prf("MIN(3,5)=%d\n",MIN(3,5));
prf("MAX(3,4)=%d\n",MAX(3,4));
prf("SQUARE(10)=%d\n",SQUARE(10));
prf("CUBE(10)=%d\n",CUBE(10));

}

{
demo;
}
Tags: 

延伸阅读

最新评论

发表评论