top of page
Writer's picturecompnomics

Function Arguments in C++: Pass by Value, Pass by Reference, and Pass by Pointer



When calling functions in C++, you can pass arguments to them in different ways: pass by value, pass by reference, and pass by pointer. Each method has its own characteristics and implications.


Pass by Value

When you pass an argument by value, a copy of the argument is created and passed to the function. Any modifications made to the argument within the function do not affect the original value outside the function.


Example:

#include <iostream>

using namespace std;

void swapByValue(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;

    swapByValue(a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

Output:

a: 10
b: 20

Pass by Reference

When you pass an argument by reference, a reference to the original argument is passed to the function. Any modifications made to the argument within the function will affect the original value outside the function.

Example:

#include <iostream>

using namespace std;

void swapByReference(int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;

    swapByReference(a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

Output:

a: 20
b: 10

Pass by Pointer

When you pass an argument by pointer, a pointer to the original argument is passed to the function. You can use the pointer to modify the original value within the function.


Example:

#include <iostream>

using namespace std;

void swapByPointer(int* x, int* y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a = 10, b = 20;

    swapByPointer(&a, &b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

Output:

a: 20
b: 10

Choosing the Right Method

  • Pass by value: Use when you want to avoid modifying the original argument within the function.

  • Pass by reference: Use when you want to modify the original argument within the function and improve performance for large objects.

  • Pass by pointer: Use when you need more flexibility in how you manipulate the argument within the function.


By understanding these different methods of passing arguments, you can write more efficient and flexible C++ code.

12 views0 comments

Recent Posts

See All

Comentários

Avaliado com 0 de 5 estrelas.
Ainda sem avaliações

Adicione uma avaliação
bottom of page