Swapnil Swapnil - 1 year ago 99
C Question

Why is const unnecessary in function declarations in header files for parameters passed by value?

I was recently reading about the usage of

keyword as function arguments in C and the way to use that has been mentioned in When and for what purposes should the
keyword be used in C for variables
and been accepted as correct answer. In this post, one point mentions that

Never use
in a function prototype for a parameter passed by
value. It has no meaning and is hence just 'noise'.

I used this way and it works for me but I am not sure why that is a noise for parameters passed by value and yet not a noise for the parameters passed by reference (more aptly the pointer values in C as there is not concept of
pass by value
pass by reference
in C). So, by this explanation when I pass a pointer as a function argument and use a
keyword; I have to do this for both the declaration in the header file and the definition in the C file but I need not use the
keyword for a non-pointer argument in the declaration (header file) and only use it while defining the function in the C file.

Any explanations?

Answer Source

The statement you quote is a bit misleading, because in C, all arguments are passed by value.* I suppose it is trying to distinguish between the arguments themselves and, for the special case of arguments that are pointers, their referents.

In any event, the point is that const-qualifying a function parameter in the function declaration conveys no information whatever to callers. Regardless of such qualification, the function cannot modify the caller's copy of any argument anyway, because arguments are passed by value.

*Note, however, that arrays are never passed at all. In function call expressions, as in most contexts, array values "decay" to pointers, and those pointers are passed by value. This produces an effect similar, but not identical, to what you would have if arrays were passed by reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download