您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
050第九章 预处理01(新版)
发布时间:2021-05-05 15:47:07编辑:雪饮阅读()
预处理的宏定义
宏其实就是一个代替作用,有点像是变量,但是变量还可以赋值之类的,而宏就是蠢蠢的一个代替而已。如下程序:
#include <stdio.h>
#define PI 3.1415926
void main( void )
{
double s;
int r;
printf("please enter the radius:");
scanf("%d",&r);
s=PI*r*r;
/*
%g用来输出实数,它根据数值的大小,自动选f格式或e格式(选择输出时占宽度较小的一种),且不输出无意义的0。
即%g是根据结果自动选择科学记数法还是一般的小数记数法
它表示以%f%e中较短的输出宽度输出单、双精度实数,在指数小于-4或者大于等于精度(这里应该指的是精度类型)时使用%e格式。
%e 浮点数、e-记数法:
数字部分(又称尾数)输出6位小数,指数部分占5位或4位。
%f 浮点数、十进制记数法
*/
printf("%g\n\n",s);
}
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
please enter the radius:2
12.5664
在引号中的宏是不会被替换的
这不废话。。。
可以看如下实例:
#include <stdio.h>
#define PI 3.1415926
void fun(void)
{
printf("Now the PI = %g\n\n", PI);
printf("PI\n\n"); // PI在引号中应该是表示常量字符串,不替换……
}
void main()
{
double s;
int r;
printf("Please enter the radius : ");
scanf("%d", &r);
s = PI * r * r;
printf("\n\nThe area of the roundness = %g\n\n", s);
fun();
}
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
Please enter the radius : 2
The area of the roundness = 12.5664
Now the PI = 3.14159
PI
宏不仅仅可以替换普通常量,也可以替换表达式,表达式中涉及其它宏也会被调用,如:
#include <stdio.h>
#define PI 3.1415926
#define S PI*r*r
void fun(void);
void main()
{
double s;
int r;
printf("Please enter the radius : ");
scanf("%d", &r);
s = S;
printf("\n\nThe area of the roundness = %g\n\n", s);
}
D:\cproject>m.exe
Please enter the radius : 2
The area of the roundness = 12.5664
宏定义typedef定义的区别
区别:宏定义只是简单的字符串代换,是在预处理完成的,而typedef是在编译时处理的,它不是作简单的代换,而是对类型说明符重新命名。被命名的标识符具有类型定义说明的功能。
如:
#include <stdio.h>
#define PIN1 char*
typedef char* PIN2;
void main()
{
/*
相当于
char* x,y
但是c中指针定义为星号向右靠近左值,而这里左值是x,那么就相当于
char *x,y
其实吧,c语言中像是char* x,y与char *x,y其实是等价的
*/
PIN1 x, y;
/*
typedef是在编译时处理的,它不是作简单的代换,而是对类型说明符重新命名。
被命名的标识符具有类型定义说明的功能。
这里相当于 char *a,*b
*/
PIN2 a, b;
char* c,d;
printf("By #define : %d %d\n\n", sizeof(x), sizeof(y));
printf("By typedef : %d %d\n\n", sizeof(a), sizeof(b));
printf("By c,d : %d %d\n\n", sizeof(c), sizeof(d));
}
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
By #define : 8 1
By typedef : 8 8
By c,d : 8 1
宏也可以应用在格式化输出
对“输出格式”作宏定义,可以减少书写麻烦。
如:
#include <stdio.h>
#define P printf
#define D "%d,"
#define F "%f\n"
void main()
{
int a = 5, c = 8, e = 11;
float b = 3.8, d = 9.7, f = 21.08;
P(D F, a, b);
P(D F, c, d);
P(D F, e, f);
}
其实我倒是没有感觉能减少了多少书写的麻烦,反而理解更麻烦了。
关键字词:预处理,宏
上一篇:049第八章 指针09(新版)
下一篇:051第九章 预处理02(新版)