Simple Exercises about Marco Definition (C)

宏定义

带参数的宏定义,与函数很像,区别在于
(1)宏定义不涉及存储空间的分配、参数类型匹配、参数传递、返回值问题
(2)函数调用在程序运行时执行,而同替换只在编译预处理阶段进行。所以带参数的宏比函数有更高的执行效率。

1. 

#include<stdio.h>

#define D(a) 2*a

int main()
{
  int b = D(3+4);
  printf("b is %d\n",b); //The calculation result would be 10 (10 = 2*3 +4), rather than 14. So the correct way to define D(a) is #define D(a) 2*(a); 
  return 0;
}

Output: b is 10


2.

#include<stdio.h>

# define PI 3.14

int main()
{
  float r,s;
  printf("Pleas input the value of radius r:\n");
  scanf("%f",&r);
  s = 2 * PI * r;
  printf("The length of this circle is %f\n",s);
  return 0;
}


Input: 1

Output: The length of this cricle is 6.280000.


3. Conditional Compilation

#include<stdio.h>

#define M 11

int main()
{
  #if M == 0
    printf("M is 0\n");
  #elif M > 0
    printf("M is greater than 0\n");
  #else
    printf("M is smaller than 0\n");
  #endif
  return 0;

Other use:

(1) #if defined(M) or #if !defined(M) // It means if M has been defined before or not been defined before, the following codes would be compiled, until #endif is met.
        ...code...
     #endif

(2) #ifdef M  or #ifndef M or #if !defined(M) // The same with above explanation.
      ...code..
      #endif



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值