Home > Net >  whats the exact rule in function declaration in c
whats the exact rule in function declaration in c

Time:09-17

I want to know is it mandatory to have constant arguments in the functions. Recently I had in interview and wrote a code like below

int numofsubstring(string s1, string s2)
{
   int nCount =0;
   size_t pos;
   while((pos = s1.find(s2)) != string::npos)
   {
     nCount  ;
     s1 = s1.substr(s1.find(s2) s2.length());
   }
    return nCount;
}  //number of times s2 is present in s1

The panel was expecting const string&s1 ,const string&s2 but i didn't wrote bcz of substr functionality usage...

can any one guide what's the standardised format to write the code.... the panel was insisting to improve the arguments in the function.

CodePudding user response:

To the extent that there is "a rule" the rule would be

if you have some function that takes a T and you can pass a const T& instead without affecting correctness then you should pass a const T&.

It's about eliminating unnecessary copies. Passing a references is like passing a pointer. Nothing gets copied so the performance of the function will be better.

CodePudding user response:

No it is not mandatory to have constant arguments in the functions. Note that the function you wrote is using pass by value. While if you had function parameters as const std::string& then it is pass by reference.

One of the reason for using const std::string& version is that in this case there will be no "copying" of passed strings, so it is faster(for very long strings) than the pass by value version.

Also in the case of pass by value the arguments passed will be copied and each of the argument will be destroyed after the function scope ends. This destruction part will not happen in the pass by reference version.

Edit: If you want that the arguments passed to the functions should not be changed inside the function body then you can add const. Below is the way to make the arguments const that is they cannot be changed inside the function body anymore.

WAY 1

//pass by value, now that we have added const the arguments s1 and s2 cannot be changed inside the function body
int numofsubstring(const string s1, const string s2)
{
//some code here
}

WAY 2

//pass by reference, now that we have added const the arguments s1 and s2 cannot be changed inside the function body 
int numofsubstring(const string& s1, const string& s2)
{
//some code here
}
  • Related