Reputation: 91
What is the difference in the following code:-
int a;
int *p;
p=&a;
function(p);
and
int a;
function(&a);
I was reading a book where sometimes they have used the first code and sometimes the other. Its not a good book though (by a local author).
Will both codes work the same way or is there any difference?
Also is there any difference in terms of efficiency and does it matter that much?
Thanks
Upvotes: 1
Views: 167
Reputation: 10285
For a reference, the object must be already existing in order to reference it. As for a pointer, the object does not need to be already existing when declaring a pointer
Example:
int &i = 10; //Invalid
const int &i = 10; //Valid
also
you cannot declare an array of references:
int &tab[] = {2,3}; //Invalid
int * tab[] = {2,3}; //Valid
In practice, reference are mostly used as functions parameters and return values;
Upvotes: 2
Reputation: 24846
As far as I know compiler implements references as pointers. So there should be no difference in performance. But references are more strict and can protect you from making mistakes. For example you can't rebind references or can't perform arithmetic with them
Also some people prefere to pass pointers to the function that modify object. For example
void changeVal(int *p)
{
*p = 10;
}
They say it's more readable when you see:
changeVal(&var)
than
changeVal(var);
EDIT
You can think of reference
as another name of the object it refers to. So all the changes made to reference
are applied to the object. Here is an example:
void foo_copy(int a) //pass by copy
{
a = 10; //changes copy
}
void foo(int &a) //bass by reference
{
a = 10; //changes passed value
}
void foo(int *a) //pass an adress of a
{
(*a) = 10; //change a value pointed by a
a = nullptr; //change a (the pointer). value is not affected
}
Upvotes: 1
Reputation: 8958
The two code snippets should be equivalent when compiled with a modern compiler. The extra declaration and assignment (p=&a;
) is optimised away.
Upvotes: 0
Reputation: 5253
In above two approaches, Both are using pointers, there is no difference except memory equal to sizeof(int *) will be allocated on stack for "int *p".
In case of call by reference, Refer. It seems you are beginner and learning things, you will come to know more about passing by reference and its use more while using copy constructor in classes.
Upvotes: 0