您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
052第九章 预处理03(新版)
发布时间:2021-05-06 11:34:04编辑:雪饮阅读()
方法躰内部添加宏
宏不僅僅只是添加在.c文件的頭部還,在方法躰内部也可以添加,只要添加在即將要用到這個宏之前,如不需要用到,則無所謂,添加到方法躰内部的末尾都可以。
#include <stdio.h>
int cmp( char *str1, char *str2 )
{
int i = 0, j = 0;
while( str1[i] )
{
while( str2[j] == str1[i] )
{
i++;
j++;
if( !str2[j] )
{
return 0;
}
}
j = 0;
i++;
}
return -1;
}
void main()
{
char str[40];
printf("Please enter the website you like the best : ");
scanf("%s", str);
#ifndef CORRECT
#define CORRECT "xkws.com"
#endif
if( cmp( str, CORRECT ) == 0 )
{
printf("\n Yeah! You are a smart man!\n\n");
}
else
{
printf("\n You fool! Man!!\n\n");
}
}
不僅僅是宏定義語句,像是宏的普通語句,如if條件表達式也可以寫在方法躰内
#include <stdio.h>
#define ROUND 0
#define PI 3.1415926
void main()
{
int r;
double s;
printf("input a number: ");
scanf("%d", &r);
#if ROUND
s = r * r * PI;
printf("Area of round is: %6.5f\n\n", s);
#else
s = r * r;
printf("Area of square is: %6.5f\n\n",s);
#endif
}
由於宏的作用是替換,所以這裏看似if,實際上是根據條件比如這裏ROUND為0,所以實際上:
s = r * r * PI;
printf("Area of round is: %6.5f\n\n", s);
這段代碼類似于被注釋了,而標準c語句的if則表示的是這段語句是有的沒有相當於被注釋,只是條件沒有達成,沒有被觸發執行而已。
編譯運行效果如:
关键字词:預處理,宏,方法體
上一篇:051第九章 预处理02(新版)