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 = 5且Y = 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
推荐的帖子
C++ Default Argument | Find output programs | Set 1
C ++默认参数| 查找输出程序| 套装1
C++ Switch Statement | Find output programs | Set 1
C ++转换语句| 查找输出程序| 套装1
C++ Switch Statement | Find output programs | Set 2
C ++转换语句| 查找输出程序| 套装2
C++ goto Statement | Find output programs | Set 1
C ++ goto语句| 查找输出程序| 套装1
C++ goto Statement | Find output programs | Set 2
C ++ goto语句| 查找输出程序| 套装2
C++ Looping | Find output programs | Set 1
C ++循环| 查找输出程序| 套装1
C++ Looping | Find output programs | Set 2
C ++循环| 查找输出程序| 套装2
C++ Looping | Find output programs | Set 3
C ++循环| 查找输出程序| 套装3
C++ Looping | Find output programs | Set 4
C ++循环| 查找输出程序| 套装4
C++ Looping | Find output programs | Set 5
C ++循环| 查找输出程序| 套装5
C++ Arrays | Find output programs | Set 1
C ++数组| 查找输出程序| 套装1
C++ Arrays | Find output programs | Set 2
C ++数组| 查找输出程序| 套装2
C++ Arrays | Find output programs | Set 3
C ++数组| 查找输出程序| 套装3
C++ Arrays | Find output programs | Set 4
C ++数组| 查找输出程序| 套装4
C++ Arrays | Find output programs | Set 5
C ++数组| 查找输出程序| 套装5
翻译自: https://www.includehelp.com/cpp-tutorial/default-argument-find-output-programs-set-2.aspx
g++默认参数