Is it possible to define the actual argument as `const int`, but declare it as" int "in the header?
See the following program.
#include <stdio.h> void f(int a); int main() { f(10); return 0; } void f(const int a) { /* a = 20; */ /* Want to avoid accidental modification of a. */ printf("%d\n", a); } In this program, declaring a function f() does not exactly match the definition. The declaration has int a as a parameter, but the definition has const int a as a parameter.
Here are my questions about this program.
- I believe this is normal, because the code that calls
f()does not need to know if the actual argumentais considered a constant withinf(). This part bit is private tof(). This does not apply to the entire calling code. As for the caller, nothing aboutint a, which is visible to him, can change whenf()called anyway. I'm right? - Is it common to declare actual arguments in function definitions as
const intorconst char *const, but declare them in the header as soon asintorconst char *? If not, do you recommend this method? To save this second question, please indicate the pros and cons of this.
Some software objects insist on tagging the const functional parameters, if possible, as there is a school of thought that assumes your function is more stable (and less vulnerable to erroneous refactoring) if you do this because you cannot inadvertently change input parameter.
In the C standard, you can use non const parameters in a function declaration and const in a definition.
Personally, I do not do this because I like my prototypes to fit my definitions. I would suggest that you too can confuse code analysis packages.