Laurijssen said:
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?
const int func(const int x, const float *f)
{
const int retval = x;
return retval;
}
has it any use to declare these as const?
Declaring the return value as 'const' won't buy you
anything, since what gets returned is a copy of it,
i.e. the caller can still change it.
const int f()
{
return 42;
}
void g()
{
int i = f();
i = 99; /* changes 'i' (the returned object with
value 42 gets destroyed before 'f()'
returns) */
}
The declaration of a 'const int' parameter might be
useful, might not. It will disallow changing the
parameter inside the function, but does not affect
the caller, since the argument is a copy of the caller's
argument.
int f(const int x)
{
x = 42; /* error: compiler must issue diagnostic */
return 0;
}
void g()
{
int i = 42;
f(i); /* 'i' is not const, but the copy
of it passed to 'f()' may not
be modified inside scope of 'f()'. */
}
=====================
int f(int x)
{
x = 42; /* ok, but has no effect on caller's argument */
}
void g()
{
int i = 0;
f(i);
/* here, 'i' still has value 0 */
}
==========================
The parameter 'const float *f' means that what the
pointer 'f' points to may not be modified. Since in
this case 'f' will point to a caller's argument, this
protects the caller's argument from changes.
int f(const float *f)
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}
void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */
f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */
}
So, if and when to use 'const' depends upon your needs.
-Mike