Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference When i write Func1(int &a) and Func1(int *a) [duplicate]

Possible Duplicate:
Difference between pointer variable and reference variable in C++

As I am starting with C++ I found the operation below confusing. I got to know about passing by reference and passing by value. But recently I came across functions like this which confused me:

Func1(int &a) 
Func2(int *a)

Both of the functions expect the address of a , but when I call Func1 I do that by Func1(a) and in case of Func2 I call by Func2(&a)

How come Func1 is accepting int a directly while it is expecting the address of a

like image 590
Simsons Avatar asked Nov 22 '10 05:11

Simsons


People also ask

What does Func1 mean?

when function definition is Func1(int &a), it means this function will accept address of variable which will pass to this function as parameter. (so you don't need to take care of passing address of variable which will parameter to function). Function default behavior will be to get address of passed variable. e.g.

Is int& the same as int &?

No, there is absolutely no difference except coding style.

What does int &A mean in C++?

1 Answer. +2. pass by reference &a means it is a reference if you change a in that function, it will change the value of the variable used for it. if you use a alone, it is pass by value. that means you can change that variable as you like and it won't change what it was called with.

What is the meaning of int&?

A int& return type simply means it returns a reference (address) of an EXISTING integer variable, same goes for int& as an argument, the function takes a reference to an integer instead of creating a new variable copy of it.


1 Answers

Func1(int &a) 
// accepts arguments by reference.
// changes to a inside Func1 is reflected in the caller
// a cannot bind to an Rvalue e.g. can't call Func1(5)
// a can never be referring to something that is not a valid object

Func2(int *a)
// accept arguments by value
// change to a inside Func1 not reflected in caller, changes to *a are
// a can bind to an Rvalue e.g. Func1(&localvar)
// a can be NULL. Hence Func2 may need to check if a is NULL
like image 103
Chubsdad Avatar answered Sep 29 '22 11:09

Chubsdad