Understanding the ‘&’ Operator in C++

c++

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?

Best Answer

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*.