【C++ Function】Three ways to pass parameters

If we wants to make a parameter-passing, there are usually three ways to go, namely common parameters, pointer parameters and quoting parameters.

  • Common parameters
    The parameters passed into the function in this form is formal parameters, which means is doesn’t change the original value outside the function. The sample code is as follows.
#include <bits/stdc++.h>
using namespace std;

void swap(int a, int b)
{
    int c = a;
    a = b;
    b = c;
}

int main()
{
    int a = 1, b = 2;
    cout << "before: a = " << a << ", b = " << b << endl;
    swap(a, b);
    cout << "after: a = " << a << ", b = " << b << endl;    
    return 0;
}

The output is as follows.

before: a = 1, b = 2
after: a = 1, b = 2

  • Pointer parameters
    The parameters passed into the function in this form is pointer parameters, which can be simply understood as two addresses. Therefore, the oprations done in the function are all based in the address, which will surely change the original value outside the function.
#include <bits/stdc++.h>
using namespace std;

void swap(int *a, int *b)
{
    int c = *a;
    *a = *b;
    *b = c;
}

int main()
{
    int a = 1, b = 2;
    cout << "before: a = " << a << ", b = " << b << endl;
    swap(&a, &b);
    cout << "after: a = " << a << ", b = " << b << endl;    
    return 0;
}

The output is as follows.

before: a = 1, b = 2
after: a = 2, b = 1

  • quoting parameters
    It’s already widely known that quoting is equivalent to aliasing, so that the ‘a, b’ in the function have the same adresses with the ‘a, b’ outside. Therefore, it will definitely change the original value outside.The sample code is as follows.
#include <bits/stdc++.h>
using namespace std;

void swap(int &a, int &b)
{
    int c = a;
    a = b;
    b = c;
}

int main()
{
    int a = 1, b = 2;
    cout << "before: a = " << a << ", b = " << b << endl;
    swap(a, b);
    cout << "after: a = " << a << ", b = " << b << endl;    
    return 0;
}

The output is as follows.

before: a = 1, b = 2
after: a = 2, b = 1

  • What’s more, I’d like to provide some interesting samples for address. This is my TODO-work.
  1. Quoting will not define a new variable, and the system won’t open up new memory space. That is, ‘a’ and ‘b’ point to the same address.
  2. Quoting is often used to pass parameters into a function. Operations for the quoting inside the function are equivalent to operating the original values outside.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值