Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++: Pointers as Function Parameters #208

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago

Concept: A pointer can be used as a function parameter. It gives the function access to the original argument, much like a reference parameter does.

// This program uses two functions that accept addressed of
// variables as arguments.

#include <iostream>

using namespace std;

// Function prototypes
void get_number(int*);
void double_value(int*);

int main() {
    int number;

    // Call get_number and pass the address of number.
    get_number(&number);

    // Call double_value and pass the address of number.
    double_value(&number);

    // Display the value in number.
    cout << "That value doubled is " << number << endl;

    return 0;
}

//****************************************************************
// Definition of get_number. The parameter, input, is a pointer. *
// This function asks the user for a number. The value entered   *
// is stored in the variable pointed to by input.                *
//****************************************************************

void  get_number(int* input) {
    cout << "Enter an integer number: ";
    cin >> *input;
}

//******************************************************************
// Definition of double_value. The parameter, val, is a pointer.   *
// This function multiplies the variable pointed to by val by two. *
//******************************************************************

void double_value(int* val) {
    *val *= 2;
}

Output:

Enter an integer number: 5
That value doubled is 10