I've been working through "C++ Primer (5th Edition)" and stumbled upon a predicament: how do I know when to use a reference as a parameter?
For example, in the following snippet of code the char parameter c is not a reference - why? Is it due to its minimal size (1 byte)?
1 2 3 4 5 6 7 8 9 10 11 12 13
string::size_type find_char(const string &s, char c, string::size_type &occurs)
{
auto ret = s.size();
occurs = 0;
for (decltype(ret) i = 0; i != s.size(); ++i) {
if (s[i] == c) {
if (ret == s.size())
ret = i;
++occurs;
}
}
}
And then there's this second code snippet; again, I do not quite grasp as to why the iterators are not references, since, in my opinion, it would be more efficient (the same goes for the int):
int sum(vector<int>::iterator, vector<int>::iterator, int);
const string &s - passed by reference because a string can be costly to copy.
char c - passed by value because it is small and cheap to copy.
string::size_type &occurs - passed by reference so that it can be modified by the function (it works as an extra return value).
The function is missing return ret; at the end.