...">

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 argument a is considered a constant within f() . This part bit is private to f() . This does not apply to the entire calling code. As for the caller, nothing about int a , which is visible to him, can change when f() called anyway. I'm right?
  • Is it common to declare actual arguments in function definitions as const int or const char *const , but declare them in the header as soon as int or const char * ? If not, do you recommend this method? To save this second question, please indicate the pros and cons of this.
+7
c parameter-passing arguments const
source share
1 answer

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.

+8
source share

All Articles