Sometimes we may want that a function should not modify the value of a parameter passed to it, either directly within that function or indirectly in some other function called form it. This can be achieved using const parameters. Consider, for example, the function given below to calculate the sum of the first n integer numbers.
You have probably noticed in below example that the function is not correct as it modifies the value of n (probably by mistake) instead of variable sum, replacing the parameter value. The compiler does not give any error or warning in this situation making the problem difficult to identify. This problem can be avoided by declaring n as a const parameter as shown below (the function body is omitted to save space).
int sum_1_n(const int n)
Now the compiler reports an error whenever the value of n is modified in the function body. Note that we can pass either a const or a non-const variable as an argument where a const parameter is expected. However, the compiler gives a warning when we pass a const variable where a non-const parameter is expected.
Finally, note that this feature is particularly useful for passing arrays and while using the call by reference mechanism.
#include <stdio.h> #include <conio.h> void main () { int a; int f,sum_1_n(); clrscr(); printf ("\n Enter a Number : "); scanf ("%d",&a); f=sum_1_n(a); printf ("\n The Sum of first %d is : %d",a,f); getch(); } /* sum of first n integer numbers (1 to n) */ int sum_1_n(const int n) { int i, sum; n = 0; for (i = 1; i <= n; i++) sum += i; return sum; }