[I edited my question to answer some of the first comments I got.]
It is well known that It is said that adding const
to function arguments when we are not planning to modify the value of the inputs within the function is regarded as both a good programming practice and a way of optimising the compilation; see, for instance, the following threads:
Just to make it clearer, I mean this:
int my_function(const int i, const my_struct *p) {
/* where `my_struct` is a large struct previously defined by me */
/* Both `i` (passed by value) and `p` (and/or `*p`?) are meant to remain unchanged during all this function */
[...]
}
However, I've read the following sentence at this C++ tutorial: https://www.cplusplus.com/doc/tutorial/functions/:
Therefore,
const
references provide functionality similar to passing arguments by value, but with an increased efficiency for parameters of large types. That is why they are extremely popular in C++ for arguments of compound types. Note though, that for most fundamental types, there is no noticeable difference in efficiency, and in some cases,const
references may even be less efficient!
So, what are those cases in which adding const
to some arguments or parameters of a function may result in a less efficient code?? Any hint or any general rule of thumb?
NOTE: I am programming in C, not in C++. I know that you can only pass variables by value in C. However, I understand that it is still useful to specify when an argument is going to remain unchanged during the function.
I insist: My question is not about passing by reference vs by value. I am programming in C, so I am assuming that arguments are passed by value. My question is about when using const
could be not advisable.
EDIT (after my question was reopened):
As some people said in the comments below, I was maybe misunderstanding the text I quoted above, since it seems to be referring to the C++ case, in which variables/arguments/parameters can be passed by reference to functions, which is not the case in C.
Anyway, in the end, my doubt was about whether using const
can be inefficient in some contexts, and I think this was already answered in the accepted answer.
My question is about when using
const
could be not advisable.
Not using const
in a function definition, to improve efficiency, is not a real concern in C.