By default,

By default, arguments in C++ are passed by value. When arguments are passed by value, a copy of the argument is passed to the function.

Consider the following snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void foo(int y)
{
    using namespace std;
    cout << "y = " << y << endl;
}
 
int main()
{
    foo(5); // first call
 
    int x = 6;
    foo(x); // second call
    foo(x+1); // third call
 
    return 0;
}

In the first call to foo(), the argument is the literal 5. When foo() is called, variable y is created, and the value of 5 is copied into y. Variable y is then destroyed when foo() ends.

In the second call to foo(), the argument is the variable x. x is evaluated to produce the value 6. When foo() is called for the second time, variable y is created again, and the value of 6 is copied into y. Variable y is then destroyed when foo() ends.

In the third call to foo(), the argument is the expression x+1. x+1 is evaluated to produce the value 7, which is passed to variable y. Variable y is once again destroyed when foo() ends.

Thus, this program prints:

y = 5
y = 6
y = 7

Because a copy of the argument is passed to the function, the original argument can not be modified by the function. This is shown in the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void foo(int y)
{
    using namespace std;
    cout << "y = " << y << endl;
 
    y = 6;
 
    cout << "y = " << y << endl;
} // y is destroyed here
 
int main()
{
    using namespace std;
    int x = 5;
    cout << "x = " << x << endl;
 
    foo(x);
 
    cout << "x = " << x << endl;
    return 0;
}

This snippet outputs:

x = 5
y = 5
y = 6
x = 5

At first, x is 5. When foo() is called, the value of x (5) is passed to variable y inside foo(). y is assigned the value of 6, and then destroyed. The value of x is unchanged, even though y was changed.

Advantages of passing by value:

  • Arguments passed by value can be variables (eg. x), literals (eg. 6), or expressions (eg. x+1).
  • Arguments are never changed by the function being called, which prevents side effects.

Disadvantages of passing by value:

  • Copying large structs or classes can take a lot of time to copy, and this can cause a performance penalty, especially if the function is called many times.

In most cases, pass by value is the best way to pass arguments to functions — it is flexible and safe.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值