Why we should sometimes write "const" before some parameters in the
function declaration or prototype? Should we put a "const" before any
input parameter? for example:
you don't have to use 'const' forr every input parameter.
'const' must be used when you don't want the argument to be changed in side the function. In,
Is there any predefined rule to pass arrays and strings always by reference?.
In general, is there any predefined rule for passing some certain kinds of
parameters (like arrays, strings, etc...) necessarily by reference/pointer or it is different in different programs??
Built in arrays are all ways passed by reference. The reason for this is when you pass an array to a function as a argument, pointer to it's first element is passed.
when you say void f(T[] array) compiler will turn it into void f(T* array)
When it comes to strings. C-style strings (i.e. null terminated character sequences) are all ways passed by reference since they are 'char' arrays too.
STL strings are not passed by reference by default. They act like normal variables.
There are no predefined rules for making parameter pass by reference.Even though the arrays are always passed by reference automatically.
But it's efficient to pass large objects by reference rather than passing them by value. Since it will consume space and time to create a replica of a large object. To ensure that the object won't change unintentionally inside the function you could use 'const' keyword.
What about vectors? I think they are not all ways passed by reference automatically like arrays and we have to put an '&' before them if we want to pass them by reference. if this is true should we pass vectors by reference always.
I have read the c++ tutorial and also searched right now but still I have problems with
two terms. I mean I can not understand what do you mean of "built in arrays" and "STL strings".
Indeed, I appreciate you if you can enlighten me.
Best Regards,
A.
Vectors are don't have to be passed by reference all ways(i presume you're referring to STL vector class. Any one can define a vector of their own).
Please note that we don't have to pass arrays by reference, it's that they are all ways passed by reference automatically.
It's true that arrays and vectors have some similarities as a data structure. But that similarity having nothing to do with the way they are passed in to the functions. So that since arrays are all ways passed by reference, it doesn't mean vectors have to be passed by reference. If you want to pass an vector by reference you should do it explicity using.
For more information about vectors visit http://www.cplusplus.com/reference/stl/vector/
I referred to as 'built in arrays' to normal arrays(sorry if i confuse you.).More about string library can be found in following article. http://www.cplusplus.com/reference/string/
sorry for a mistake i made in my above post, i refereed to string provided by string library as 'STL String'.