BP-4-5 Further Discussion on C++ Functions

Chapter 04 Procedural Abstraction - Function

6. Further Discussion on C++ Functions

6.1 Macro with Parameters
#define <macro-name> (<parameter-list>) <expression>
//example:
#define max(a, b) (((a) > (b)) ? (a) : (b))

Macro is inherited from C and can solves the problem of inefficiency of frequent call to small functions.

The implementing rule for macro with parameters is direct substitution without any checking, which might bring some problems.

6.2 Inline Function
inline <a-function-definition>

Inline function is defined just put the keyword inline before the regular function definition. Which has similar function to macro but will check the data type, which is safer than macro.

But the keyword inline just suggest the compiler to deal with when compiling, whether the suggestion is going to be taken depends on the compiler.

And we usually put the definition of inline function in the header file.

6.3 Parameters with Default Value

We can give the parameter a default value when defining or declaring it, but there are some rules to follow:

  • Assign default value from right to left;
  • A parameter can only be assigned one default value in the same file.
6.4 Function Overloading

In C++, the two function can share the same name if they’ve got some difference in parameters in terms of number of parameters or their data types, which is called function overloading.

6.5 Anonymous Function - Lambda Expression
[<environment-announcement>] (<parameter-list>) -> <return-value-type> <function body>;
//example: call expression include a lambda expression
int n = [] (int x, int y)->int {return x + y;} (3, 4); 

About the environment-announcement:

  • : We can’t use variables in the outer scope;
  • & : We can use variables in the outer scope as a quota, which means you can modify them;
  • = : We can use variables in the outer scope by value, which means you can’t modify them.

More information will be talked later when we discuss passing in a function as an argument.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值