g++默认参数_C ++默认参数| 查找输出程序| 套装2

g++默认参数

Program 1:

程序1:

#include <iostream>
using namespace std;

int K = 10;

int fun()
{
    return K;
}
int sum(int X, int Y = fun())
{
    return (X + Y);
}

int main()
{
    int A = 0;

    A = sum(5);
    cout << A << " ";

    K = 20;
    A = sum(5);
    cout << A << " ";

    return 0;
}

Output:

输出:

15 25

Explanation:

说明:

Here, we defined two functions fun() and sum().

在这里,我们定义了两个函数fun()sum()

The fun() function returns the value of global variable K. and function sum() take the second argument as a default argument, here we use fun() as a default value of the Y. If we modify the value of global variable K, then the default value will be changed automatically. 

fun()函数返回全局变量 K的值。 函数sum()将第二个参数作为默认参数,这里我们将fun()用作Y的默认值。 如果我们修改全局变量K的值,那么默认值将自动更改。

Now come to the function calls,

现在来看函数调用,

1st function call:

第一个函数调用:

A = sum(5);

Here, X = 5 and Y =10, because the value of K is 10 till now. then function return 15. 

在此, X = 5Y = 10 ,因为到目前为止K的值为10。 然后函数返回15。

2nd function call:

第二次函数调用:

A = sum(5);

Before the second function call, we modify the value of the global variable K. The new value of K is 20. Then X = 5 and Y =20. Then function sum() return 25.

在第二个函数调用之前,我们修改全局变量K的值。 K的新值为20。然后X = 5,Y = 20。 然后函数sum()返回25。

Then the final output "15 25" will be printed on the console screen.

然后,最终输出“ 15 25”将被打印在控制台屏幕上。

Program 2:

程式2:

#include <iostream>
#define NUM 10 + 20
using namespace std;

int fun(int X = NUM)
{
    return (NUM * NUM);
}

int main()
{
    int RES = 0;

    RES = fun();

    cout << RES;

    return 0;
}

Output:

输出:

230

Explanation:

说明:

Here, we defined function fun() that takes macro NUM as a default value of the argument.

在这里,我们定义了函数fun() ,该函数将宏NUM作为参数的默认值。

Now, evaluate the expression used in the return statement,

现在,评估return语句中使用的表达式,

NUM*NUM
10+20*10+20
10+200+20
230

Then function fun() will return 230, and that will be printed on the console screen.

然后,函数fun()将返回230 ,并将其打印在控制台屏幕上。

Recommended posts

推荐的帖子

翻译自: https://www.includehelp.com/cpp-tutorial/default-argument-find-output-programs-set-2.aspx

g++默认参数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值