Is it true that (const T v) is never necessary in C?
For example:
void func(const int i);
Here,the const
is u开发者_JS百科nnecessary since all parameters are passed by value(including pointers).
Is that true?
All parameters in C are indeed passed by value, which means that the actual argument will not change regardless of whether you include that const
or not.
However, that does not mean that const
here is "never necessary". Whether it is necessary or unnecessary depends on what you want to achieve.
If you want to prevent any attempts to modify the parameter inside the function, then the const
is necessary, of course.
There is a fairly popular (and pretty reasonable) coding guideline that says that function parameters should never be modified inside the function, i.e. that at any point of function's execution all parameters must retain their original values. Under this guideline it would actually make perfect sense to always include that const
in all parameter declarations.
const is just used by the precompiler, to notice about errors...
Note that this is perfectly valid:
void foo( const char * bar )
{
char * baz = ( char * )bar;
baz++;
}
So it's never necessary, but it just makes the code more readable, and informs you the pointer should never change...
精彩评论