Re: C++ noob question.
@usernamer: C++ and C do have the same syntax for working with pointers, but this is an additional feature of C++. It's a prefix to a function parameter or variable that says it is a reference. It uses the same "&" character as the "address of" in C, but it's not the same thing.
@OP: In the case of passing what you might call an "out" parameter, obviously the syntax of the pointer and reference is slightly different:
Pointer
Code:
void increment(int *x)
{
*x = *x + 1;
}
int main()
{
int value = 0;
increment(&value);
cout << value << endl;
}
Reference
Code:
void increment(int &x)
{
x = x + 1;
}
int main()
{
int value = 0;
increment(value);
cout << value << endl;
}
The result is the same in both cases.
But there's more to it than syntax. A reference is like a pointer with conditions attached:
- It can't be NULL
- It can't be reassigned to refer to something else
- It can't be manipulated, e.g. incremented to point at the next entry in an array
Sometimes it's more appropriate to work with a pointer, e.g. if you want to work with the idea of null, or if you want to manipulate it. Other times it's a better fit to work with a reference. In the increment function above, I think a reference fits the intent of the function better than a pointer. (I don't want to manipulate it and it shouldn't be null).
Please create new threads for new questions.
Please wrap code in code tags using the '#' button or enter it in your post like this: [code]...[/code].
Bookmarks