Yelp Interview Question
AnalystsCountry: United States
Interview Type: Phone Interview
With the second having a const parameter too.
The vector 'vec' can't be modified inside this function.
Beware of this so seemingly simple questions. Everybody already knows about "const" and passing by value vs. reference. Answering this I think will be considered newbie answers by a competent interviewer.
The real answer comes along the r-value vs. l-value differences in C++... and temporary objects. The first implementation is a pass-by-value, ok, it involves copies and all that, but it becomes an l-value local to the function, always.
The second one, however WITHOUT "const" is a pass-by-reference and it will be an l-value iff the original is also an l-value, but will be an r-value if a temporary object is involved (perhaps by default conversion into a vector<int>). The C++ standard forbids temporary objects to be l-values, so a compilation error will occur if there needs to be a default conversion.
Adding "const" allows again a conversion on the calling on the function since it will allow for r-values to be passed (remember the "const").
It's a tricky question more easily understood with an example for std::string:
// Pass by value
void doSomething1(std::string str)
{
}
// Pass by reference, non-const
void doSometing2(std::string &str)
{
}
// Pass by reference, const
void doSomething3(const std::string &str)
{
}
// Allowed, a temporary of type std::string is default constructed
// and passed to the function
doSomething1("Whatever");
// Forbidden, function expects a non-const reference and we
// must default construct a temporary, hence an r-value
doSomething2("Whatever");
// Allowed, a temporary of type std::string is default constructed
// and allowed to pass since the function expects a const reference
doSomething3("Whatever");
#include <iostream>
#include <vector>
using namespace std;
void test1(vector<int> arr);
void test2(const vector<int> &arr);
int main()
{
vector<int> arr;
for(int i=0;i<10;i++) {
arr.push_back(i);
}
test1(arr);
test2(arr);
return 0;
}
void test1(vector<int> arr) {
for(int i=0;i<arr.size();i++) {
cout<<arr.at(i)<<endl;
}
}
void test2(const vector<int> &arr) {
for(int i=0;i<arr.size();i++) {
cout<<arr.at(i)<<endl;
}
}
// When testing it, there is no difference in output.
One is pass by value, another pass by reference. Pass by value will make a copy of data, possibly much slower and using more memory.
- dn May 14, 2013