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 the declaration of the function f()
does not exactly match the definition. The declaration has int a
as the parameter but the definition has const int a
as the parameter.
Here are my questions about this program.
f()
doesn't have to know whether the actual argument a
is treated as constant within f()
. That bit of detail is private to f()
. That's none of the calling code's concern. As far as the caller is concerned, nothing about int a
that is visible to it can change while calling f()
in either case. Am I right?const int
or const char *const
but declare them in the header as just int
or const char *
? If not, do you recommend this way? To keep this second question objective, please list the pros and cons of doing this.Some software houses insist on marking function parameters const
if possible as there is a school of thought that suggests your function is more stable (and less vulnerable to errant refactoring) if you do that since you can't unintentionally modify an input parameter.
The C standard allows you to use non-const
parameters in a function declaration, and const
in the definition.
Personally I don't do it as I like my prototypes to match my definitions. I'd imagine that you could confuse code analysis packages too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With