面试1----5预处理之宏操作

1 这里主要是#ifdef #else #endif使用

(1)下面的程序是:通过用户输入字母,输出如下

(2)代码如下

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define DEBUG
 5 int main()
 6 {
 7     int i = 0;
 8     char c;
 9     while (1)
10     {
11         i++;
12         c = getchar();
13         if (c != '
')
14         {
15             getchar();
16         }
17         if (c == 'q' || c == 'Q'){
18 #ifdef DEBUG
19             printf("we got:%c,about to exit
", c);
20 #endif
21         }
22         else
23         {
24             printf("i=%d", i);
25 #ifdef DEBUG
26             printf(",we got:%c", c);
27 #endif
28             printf("
");
29         }
30     }
31     return 0;
32 }
View Code

(3)代码讲解

  代码上面咋们定义了宏#DEBUG的预处理常量,代码的后面用#ifdef(如果定义了)那么就是打印输出的信息(简单调试的时候是不是不用那么麻烦的去删除代码了呢!),相反没有被定义就不会输出了哦

 2 用#define实现宏并求最大值和最小值

(1)下面程序是:分别求出最大值和最小值

(2)代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define MAX(x,y) (((x)>(y))?(x):(y))
 5 #define MIN(x,y) (((x)<(y))?(x):(y))
 6 int main()
 7 {
 8     printf("最大值%d
", MAX(2, 3));
 9     printf("最小值%d
", MIN(2, 3));
10     getchar();
11     return 0;
12 }
View Code

(3)代码注意细节:

  在宏中需要把参数小心的括起来哦,因为宏只是简单的文本替换

3 宏定义的使用(这个题目要小心了哦)

(1)看看这个代码会输出什么??一定要思考哦!

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define SQR(x) (x*x)
 4 int main()
 5 {
 6     int a, b = 3;
 7     a = SQR(b + 2);
 8     printf("a=%d
", a);
 9     getchar();
10     return 0;
11 }
View Code

-------->你的结果是25?恭喜你答错了,咱们看看到底是怎么个情况呢

(2)代码总结

  a:咱们是不是理解成了这样:a = (b+2)*(b+2),ok,注意了,因为宏定义展开的时候发生在预处理时期,也就是在编译之前,着个时候b并没有赋值,所以呢b这个时候就只是一个符号,也就是(b+2*b+2)------>这样的结果就是11

  b:这不是我们想要的结果,那就加上括号 #define SQR(X) ((X)*(X))

4 宏参数的传递

(1)同样先看看会输出什么?

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define STR(s) #s
 4 #define CONS(a,b) (int)(a##e##b)
 5 int main()
 6 {
 7     printf(STR(vck));
 8     printf("
");
 9     printf("%d
", CONS(2, 3));
10     getchar();
11     return 0;
12 }
View Code

正确答案:

(2)代码总结

  a:使用#把宏参数变化为字符串 用##将两个宏连接在一起

  b:CONS(a,b)-----》j将参数a与b按照aeb连接起来的一个整数,所以就是2e3--->2000 ok

5 用宏定义得到一个数组的元素个数

(1) int占4字节,如果100个int'元素那么就有400个字节,那么sizeof(array[0])就是一个int大小,所以见下代码

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define ARR_SIZE(a) (sizeof((a))/sizeof(a[0]))
 5 int main()
 6 {
 7     int ARRAY[100];
 8     printf("数组元素%d个
", ARR_SIZE(ARRAY));
 9     getchar();
10     return 0;
11 }
View Code

(2)注意为了保证宏定义不产生二义性,在a和a[0]都加上了括号

--------->

  -------->好了,今天就到这了,小伙伴们加油哦!

原文地址:https://www.cnblogs.com/lanjianhappy/p/7900250.html