I know the & operator means address-of, but what's it do when in a function prototype?

Example:

void foo(std::string& str)

or

void foo(char& c)

what's the & for in that?

Dani AI

Generated

As explained, the ampersand in a parameter declaration is the reference declarator (a type modifier), not the unary address-of operator. In declarations it makes the parameter an alias for an existing object; in expressions the same symbol is the address-of operator. That contextual difference is why the same character appears in both roles.

Key rules and pitfalls: a reference must be bound when created and cannot be reseated; a plain T& requires an lvalue argument while const T& can bind to temporaries (and extends their lifetime to the reference). References are not nullable in the language sense (uninitialized or null references lead to undefined behavior). Returning a reference to a local object is a common mistake and produces a dangling reference. Example:

int& bad() {
    int x = 7;
    return x; // dangling reference — undefined behavior
}

const int& ok = 42; // binds to temporary; lifetime extended to ok

Practical guidance: pass small, trivially-copyable types (ints, chars, pointers) by value. For large objects that should not be modified, prefer const T& to avoid copying. When the function needs to take ownership in modern C++, prefer pass-by-value and move (T param then std::move(param)) or provide an overload taking T&& to enable move semantics:

void process(std::vector<int> v);           // copy / take ownership
void process(const std::vector<int>& v);    // read-only, no copy
void process(std::vector<int>&& v);         // accept temporaries / move

For authoritative details and edge cases see the cppreference pages on references, lifetime rules, rvalue references, and std::move: , lifetime, rvalue references, std::move.

I know the & operator means address-of, but what's it do when in a function prototype?

Example:

void foo(std::string& str)

or

void foo(char& c)

what's the & for in that?

The & symbol means that you are passing the parameter to the function by "reference" rather than by "value". When the & symbol is next to a parameter, if you change that parameter in the function, that will change the variable that was passed to it when the function was called.

For example,

void foo(char& c)
{
     c = 'a';
}

If the code below was executed:

char x;
foo (x);
cout << x;

the output would be this:

a
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.