Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing strings by reference and value in C++

I want to declare a string, initialize it by passing it by reference, and then pass it by value to the 'outputfile' function.

The code below works, but I don't know why. In main I would expect to pass the string 'filename' like

startup(&filename)

But that gives an error, and the code below doesn't. Why? Also, is there a better way to do this without using a return value?

#include <iostream>
#include <string>
using namespace std;
void startup(std::string&);
void outputfile(std::string);
int main()
{
    std::string filename;
    startup(filename);
    outputfile(filename);
}   
void startup(std::string& name)
{
    cin >> name;
}
void outputfile(std::string name)
{
    cout << name;
}
like image 371
Peter Avatar asked Feb 08 '15 05:02

Peter


People also ask

Are strings passed by value or reference in C?

In this sense, the correct answer would be: strings are passed by reference. The built in string type is a value type. Variables (also function/method arguments from now on) and struct fields of type string are passed/copied by value.

Is string passed by reference or value?

Strings are Reference/Complex Object Type It means, since the string variable holds the reference to the actual data, so it passes this reference and not the actual data. So, it's pass by value!

How do you pass a string by passing by reference?

First, we have the function definition “DisplayString,” where a constant string reference is passed. The constant strings are defined and initialized in the main function as “str1” and “str2”. After that, pass these constant strings to the function “InputString”.

What is pass by value and pass by reference in C?

The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function can not affect the calling function.


1 Answers

Your code works as expected.

&filename returns the memory address of (aka a pointer to) filename, but startup(std::string& name) wants a reference, not a pointer.

References in C++ are simply passed with the normal "pass-by-value" syntax:

startup(filename) takes filename by reference.


If you modified the startup function to take a pointer to an std::string instead:

void startup(std::string* name)

then you would pass it using the address-of operator:

startup(&filename)


As a side note, you should also make the outputfile function take its parameter by reference, because there's no need to copy the string. And since you're not modifying the parameter, you should take it as a const reference:

void outputfile(const std::string& name)

For more info, here are the rules of thumb for C++ regarding how to pass function parameters.

like image 98
emlai Avatar answered Sep 28 '22 20:09

emlai