简体   繁体   中英

Is it true that (const T v) is never necessary in C?

For example:

void func(const int i);

Here,the const is unnecessary 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, ie 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM