Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to define the actual argument as `const int` but declare it as just `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 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.

  1. I believe this is okay because, the code that calls 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?
  2. Is it common to declare the actual arguments in the function definitions as 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.
like image 805
Lone Learner Avatar asked May 19 '16 13:05

Lone Learner


1 Answers

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.

like image 78
Bathsheba Avatar answered Sep 27 '22 20:09

Bathsheba