PDA

View Full Version : Passing references vs pointers as function parameters



arcull
26th August 2015, 10:35
Hi.
This post is somewhat related to this onehttp://www.qtcentre.org/threads/63447-A-shortcut-please-%29, but have rather opened new one to avoid confusion. So the question is simple, but the answer is not, at least for me ;) How much do these two approaches differ at all in a techical sence? Which one would you use in which case and why? Consider these two code snippets bellow, got from http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators and http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm


#include<iostream>
using namespace std;

void swapping(int *ptr_c, int *ptr_d)
{
int tmp;

tmp = *ptr_c;
*ptr_c = *ptr_d;
*ptr_d = tmp;
cout << "In function:\n" << *ptr_c << '\n' << *ptr_d << '\n';
}

void main()
{
int a,b;

a=5;
b=10;
cout << "Before:\n" << a << '\n' << b << '\n';
swapping(&a,&b);
cout << "After:\n" << a << '\n' << b << '\n';
}



// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */

return;
}

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/
swap(a, b);

cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}

arcull
26th August 2015, 18:06
I see this one is tough for you too ;) but I guess there must some guru here knowing this.

anda_skoa
26th August 2015, 18:46
std::swap uses references: http://en.cppreference.com/w/cpp/algorithm/swap

Cheers,
_

d_stranz
26th August 2015, 20:51
How much do these two approaches differ at all in a techical sence?

Technically, they are identical. Functionally, references are guaranteed to be valid, whereas pointers may be valid, invalid, or NULL. Passing a bad pointer into the pointer-based method will either cause a crash or corruption of memory or stack.

arcull
26th August 2015, 21:07
std::swap uses references: http://en.cppreference.com/w/cpp/algorithm/swap

Cheers,
_ Ok thanks, that can indicate a preferred way, but it doesn't answer the question.


Technically, they are identical. Functionally, references are guaranteed to be valid, whereas pointers may be valid, invalid, or NULL. Passing a bad pointer into the pointer-based method will either cause a crash or corruption of memory or stack. Good, I agree