// 预处理指令
/*
1、宏定义指令
2、文件包含指令
3、条件编译指令
*/
// 宏只是替换,不做语法检查,不分配内存,宏的作用从开始到文件结束
// 无参宏
#define HELLO printf("hello world!\n");
// 宏嵌套
#define R 10
#define PI 3.1415926
#define S PI*(R*R)
// 终止宏
#undef R
// 带参宏
#define Sum(a) a*a
// 带参宏运用
#define ABS(x) ((x)>=0) ? x : -(x)
// 包含文件指令
#include "CTest.h"
// 条件编译,就是有条件地编译,满足条件时即编译,不满足即不编译
// #if #endif运用,检测宏的值
void test()
{
// 先宏定义
#define NUM 'c'
// 再判断
#if NUM == 'e'
printf("The treasure of pirate is buried under your bed!\n");
#else
printf("海盗的宝藏就藏在你的床下!\n");
#endif
}
// elif运用
void test1()
{
#define WORD 'c'
#if WORD == 'e'
printf("English!\n");
#elif WORD == 'l'
printf("Life Cube\n");
#elif WORD == 'h'
printf("hello world\n");
#else
printf("中国\n");
#endif
}
// ifdef运用,检测宏是否定义
void test2()
{
#define MOD 111
#ifdef MOD
printf("MOD已经定义!\n");
#else
printf("MOD没有定义!\n");
#endif
}
// ifndef运用,检测宏是否没有被定义
void test3()
{
#ifndef BOOK
#define BOOK
struct book
{
char namr[20];
float price;
};
#endif
}
void test4()
{
#ifdef __cplusplus
#endif
printf(">>>>>>>>>>>>>>>\n");
#ifdef __cplusplus
#endif
}
/*
预定义宏
__DATE__ // 进行预处理的日期,类型:字符串
__FILE__ // 代表当前源代码文件名的字符串文字,类型:字符串
__LINE__ // 代表当前源代码中的行号,类型:整数
__TIME__ // 源文件编译时间,类型:字符串
__FUNCTION__ //__func__ // 只在函数中有效,返回当前函数的函数名,类型:字符串
__STDC__ // 该宏被定义后,编译器按照ANSI C标准来编译C程序
__cplusplus // C++预定义宏,当建立C++工程时,该宏就会被定义
*/
void test6()
{
printf("该语句所在函数名:%s\n",__FUNCTION__);//__func__
printf("当前文件为:%s\n",__FILE__);
printf("当前代码所在行数为:%d\n",__LINE__);
printf("编译日期为:%s\n",__DATE__);
printf("编译时间为:%s\n",__TIME__);
}
#include <assert.h>
// assert()参数为真时,返回真,参数为假时,抛出异常
void test7()
{
float a,b;
printf("请输入除数b的值:");
scanf("%f",&b);
printf("请输入被除数a的值:");
scanf("%f",&a);
assert(b!=0);
printf("运算结果为:%.2f\n",a/b);
}
C语言_预处理命令
最新推荐文章于 2023-07-31 21:24:29 发布