Lets say we have a variable we want to change through a function.
What is the best way to do this, is one method better than another?
Is there a better way to do that.Code:int number; void ChangeNumber(int &number) { // change number }
Lets say we have a variable we want to change through a function.
What is the best way to do this, is one method better than another?
Is there a better way to do that.Code:int number; void ChangeNumber(int &number) { // change number }
What is C++?
You should prefer using references unless it's possible to pass a "nothing" object, in which case you have no choice but to use pointers because there's no such thing as a null reference.
My best code is written with the delete key.
Just to make sure I understand.
I am at a point in programming where I have just recently started to learn the language. I have used C++ for about 2-3 years but I just toyed with it. I am just now getting into it and learning how/why it works.Code:void ChangeNumber(int *number) { // change number }
So the & operator gets the address-of and * creates a reference.
Now, what is it actually doing. I understand that the & operator passes the memory location of the variable. But what does * do?
What is C++?
& is the address-of when used with a variable
& means its a reference when used with parameters and variable declartions
* means its a pointer when used with parameters and variable declartions
* means to deference a pointer when used with a variable
Code:int a = 10; int *b; // B is a pointer b = &a; // &a is the address of a int &c = a; // &c means c is a reference to a *b = 10; // go to the location b points to and change its value to 10
>So the & operator gets the address-of and * creates a reference.
No, not really. Operators in C++ are overloaded to do different things based on the context. When used in a declaration, the ampersand means that you are creating a reference:
When used as a value, the ampersand takes the address of an object:Code:int i = 5; int& ri = i; // Any changes to ri reflect i
It also does other things, such as bitwise AND, but we'll ignore that for now.Code:int i = 5; cout<< &i <<endl; // Prints i's address
The asterisk in a declaration creates a pointer (ie. a variable that holds an address):
When used in an expression, the asterisk means to dereference a pointer so that you are looking at the contents of the address rather than the address itself:Code:int i = 5; int *pi = &i; // pi "points to" i
Code:cout<< *pi <<endl; // Prints 5 because pi points to i
My best code is written with the delete key.
Thank you both for the info.
What is C++?