[Macro/Inline Function] Try Them!

[Macro/Inline Function] Try Them!

  • 题目描述
  • 答题区域
  • 提交记录
  • 成绩报告
  • 排名情况
  • 标准答案
  • 相关讨论
出题
邮箱
卢家熙
914670787@qq.com
评测
截止时间
实时评测
2018-03-19 23:59
空间限制
时间限制
32MB
1000ms

Try Macro and Inline Function

Description

Use macro and inline function to implement swap and max .

Detail

swap means swap two variables. Will be used as swap(a, b); .

max means select and return the bigger one of two variables. Will be used as int res = max(a, b); .

In this assignment, implement inline int inline_MAX(int a, int b) and inline void inline_SWAP(int &a, int &b) with inline function , and implement MACRO_MAX(a, b) and MACRO_SWAP(a, b) with macro .

In this assignment, you must use macro or you will get in trouble. (But be aware that macro is NOT always a good solution!)

Hint

简单来说,内联函数(inline function)就是会在调用处被展开的函数,这听起来会有点像宏里面的 #define 指令,比如 #define MAX_LEN 100 会在预处理时把 MAX_LEN “展开”成 100,而它们的不同在于宏指令 #define 是单纯的字符串替换,而内联函数不是。 (内联函数被如何处理呢?)

本题的意思就是使用 #define 的其中一种带参数的用法来实现类似函数的功能,关于在本题中的用法,可以参考这篇博客中的第2点,更推荐参考gnu的cpp文档中的 Function-like Macros 和 Macro Arguments 的部分。

需要注意的一点是,#define 是一种字符串替换,所以可能出现一种不易发现的问题,如:

#define ADD(x,y) x + y
int foo(int a, int b) {
    return 3 * ADD(a + 2, b) * 2;
}

在这种情况下,第3行会被替换成 return 3 * a + 2 + y * 2; ,与预期的效果不符。因此使用宏时必须小心,在这里应该改写为 #define ADD(x,y) ((x) + (y))

(这里是这道题的答案……)

#define 用法举例,取两个数中小的一个: #define MIN(x, y) ((x) < (y) ? (x) : (y))

一行代码交换两个int: a ^= b ^= a ^= b;

另外本题的函数命名并不是规范,请不要盲从……

  • my_inline.hpp
  • my_macro.hpp
  • main.cpp
1
#include <iostream>
2
#include <cassert>
3
4
#include "my_macro.hpp"
5
#include "my_inline.hpp"
6
7
#include "check_macro.hpp"
8
9
using std::cout;
10
using std::cin;
11
using std::endl;
12
13
int main() {
14
  // Check if you really use a macro to do this
15
  CHECK_MACRO;
16
17
  int a = 0, b = 0;
18
  cin >> a >> b;
19
  cout << a << " " << b << endl;
20
21
  int res = inline_MAX(a, b);
22
  cout << "inline_MAX: " << res << endl;
23
  inline_SWAP(a, b);
24
  cout << "inline_SWAP: " << a << " " << b << endl;
25
26
  res = MACRO_MAX(a, b);
27
  cout << "MACRO_MAX: " << res << endl;
28
  MACRO_SWAP(a, b);
29
  cout << "MACRO_SWAP: " << a << " " << b << endl;
30
  
31
  return 0;
32

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值