What does '&' mean in C++?
As within the function
void Read_wav::read_wav(const string &filename)
{
}
And what is its equivalent in C?
If I want to transform the above C++ function into a C function, how would I do it?
In that context, the & makes the variable a reference.
Usually, when you pass an variable to a function, the variable is copied and the function works on the copy. When the function returns, your original variable is unchanged. When you pass a reference, no copy is made and changes made by the function show up even after the function returns.
C doesn't have references, but a C++ reference is functionally the same as a pointer in C. Really the only difference is that pointers have to be dereferenced when you use them:
*filename = "file.wav";
But references can be used as though they were the original variable:
filename = "file.wav";
Ostensibly, references are supposed to never be null, although it's not impossible for that to happen.
The equivalent C function would be:
void read_wav(const char* filename)
{
}
This is because C doesn't have string
. Usual practice in C is to send a pointer to an array of characters when you need a string. As in C++, if you type a string constant
read_wav("file.wav");
The type is const char*
.
It means that the variable is a reference. There is no direct equivalent in C. You can think of it as a pointer that is automatically dereferenced when used, and can never be NULL, maybe.
The typical way to represent a string in C is by a char
pointer, so the function would likely look like this:
void read_wav(struct Read_wav* instance, const char *filename)
{
}
Note: the first argument here simulates the implicit this
object reference you would have in C++, since this looks like a member method.
The ampersand is used in two different meanings in C++: obtaining an address of something (e.g. of a variable or a function) and specifying a variable or function parameter to be a reference to an entity defined somewhere else. In your example, the latter meaning is in use.
C does not have strictly speaking anything like the reference but pointers (or pointers to pointers) have been user for ages for similar things.
See e.g. http://www.cprogramming.com/tutorial/references.html, What are the differences between a pointer variable and a reference variable in C++? or http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29 for more information about references in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With