hen passing arguments

When passing arguments by value, the only way to return a value back to the caller is via the function’s return value. While this is suitable in many cases, there are a few cases where better options are available. One such case is when writing a function that needs to modify the values of an array (eg. sorting an array). In this case, it is more efficient and more clear to have the function modify the actual array passed to it, rather than trying to return something back to the caller.

One way to allow functions to modify the value of argument is by using pass by reference. In pass by reference, we declare the function parameters as references rather than normal variables:

1
2
3
4
void AddOne( int &y) // y is a reference variable
{
     y = y + 1;
}

When the function is called, y will become a reference to the argument. Since a reference to a variable is treated exactly the same as the variable itself, any changes made to the reference are passed through to the argument!

The following example shows this in action:

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

This program is the same as the one we used for the pass by value example, except foo’s parameter is now a reference instead of a normal variable. When we call foo(x), y becomes a reference to x. This snippet produces the output:

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

Note that the value of x was changed by the function!

Here is another example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void AddOne( int &y)
{
     y++;
}
 
int main()
{
     int x = 5;
 
     cout << "x = " << x << endl;
     AddOne(x);
     cout << "x = " << x << endl;
 
     return 0;
}

This example prints:

x = 5;
x = 6;

As you can see, the function was able to change the value of the argument.

Sometimes we need a function to return multiple values. However, functions can only have one return value. One way to return multiple values is using reference parameters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <math.h>    // for sin() and cos()
 
void GetSinCos( double dX, double &dSin, double &dCos)
{
     dSin = sin (dX);
     dCos = cos (dX);
}
 
int main()
{
     double dSin = 0.0;
     double dCos = 0.0;
 
     // GetSinCos will return the sin and cos in dSin and dCos
     GetSinCos(30.0, dSin, dCos);
 
     std::cout << "The sin is " << dSin << std::endl;
     std::cout << "The cos is " << dCos << std::endl;
     return 0;
}

This function takes one parameter (by value) as input, and “returns” two parameters (by reference) as output.

Pass by const reference

One of the major disadvantages of pass by value is that all arguments passed by value are copied to the parameters. When the arguments are large structs or classes, this can take a lot of time. References provide a way to avoid this penalty. When an argument is passed by reference, a reference is created to the actual argument (which takes minimal time) and no copying of values takes place. This allows us to pass large structs and classes with a minimum performance penalty.

However, this also opens us up to potential trouble. References allow the function to change the value of the argument, which in many cases is undesirable. If we know that a function should not change the value of an argument, but don’t want to pass by value, the best solution is to pass by const reference.

You already know that a const reference is a reference that does not allow the variable being referenced to be changed. Consequently, if we use a const reference as a parameter, we guarantee to the caller that the function will not (and can not) change the argument!

The following function will produce a compiler error:

1
2
3
4
void foo( const int &x)
{
     x = 6;  // x is a const reference and can not be changed!
}

Using const is useful for several reasons:

  • It enlists the compilers help in ensuring values that shouldn’t be changed aren’t changed.
  • It tells the coder whether they need to worry about the function changing the value of the argument
  • It helps the coder debug incorrect values by telling the coder whether the function might be at fault or not

Rule: Always pass by const reference unless you need to change the value of the argument

Summary

Advantages of passing by reference:

  • It allows us to have the function change the value of the argument, which is sometimes useful.
  • Because a copy of the argument is not made, it is fast, even when used with large structs or classes.
  • We can pass by const reference to avoid unintentional changes.
  • We can return multiple values from a function.

Disadvantages of passing by reference:

  • Because a non-const reference can not be made to a literal or an expression, reference arguments must be normal variables.
  • It can be hard to tell whether a parameter passed by reference is meant to be input, output, or both.
  • It’s impossible to tell from the function call that the argument may change. An argument passed by value and passed by reference looks the same. We can only tell whether an argument is passed by value or reference by looking at the function declaration. This can lead to situations where the programmer does not realize a function will change the value of the argument.
  • Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.
"Kao足球真是一项受到广泛关注的运动。" 足球,作为一项全球性的运动,受到了世界各地人们的热爱和关注。它不仅仅是一项运动,更是一种文化和激情的象征。在球场上,球员们通过技术、策略和团队合作展示出令人惊叹的精彩表演。 足球的吸引力在于它的简单和普及性。只需一颗球和一个开阔的场地,就能让任何人参与其中。这使得足球成为了广大人群喜爱的运动,而且它能够连接人们并跨越语言和文化的界限。 足球不仅仅是一场比赛,它还是团队精神和合作的体现。球队中的每个球员都有自己的角色和职责,只通过彼此的配合和默契才能取得胜利。这不仅培养了个人的团队合作能力,也让球员们学会了互相信任和支持。在球迷眼中,他们更看重球队的精神氛围和团结程度。 此外,足球还有一种独特的激情和情感。球迷们通过观看比赛,与自己心仪的球队和球员建立起了紧密的情感联系。他们会为球队的胜利欢欣鼓舞,也会为球队的失败失落沮丧。这种激情和情感使得足球成为了一项与众不同的运动,无论是球员还是球迷都为之痴迷。 总而言之,足球的吸引力在于它的普及性、团队合作精神和丰富的情感体验。正因为如此,足球在世界范围内得到了广泛关注和喜爱。无论是球场上的竞技表演,还是球迷间的激情呐喊,都让人欣赏和陶醉其中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值