bunny bugs
bunny bugs

Reputation: 35

can anyone please explain me the need for & in the first code snippet

In the following snippet of code I have noticed ampersand is used even though we aren't manipulating the string. Can anyone please tell me why it's needed?

bool compare(string &s1,string &s2) 
{ 
    return s1.size() < s2.size(); 
} 

Snippet 2: would this code work?

bool compare(string s1,string s2) 
{ 
    return s1.size() < s2.size(); 
} 

Upvotes: 0

Views: 37

Answers (1)

CoderCharmander
CoderCharmander

Reputation: 1910

The & sign (reference) is needed, because this way the program will only use a reference to the original string. If you don't use a reference, then the program will copy the string, so the program will be

  • A bit slower
  • Less memory effective

A const reference (const string&) is even better, because it will make it read-only, so you can pass string literals. Like compare("abc", "foo bar").

Yes, your second snippet would work, but it's not recommended.

Upvotes: 3

Related Questions