by Dinesh Thakur Category: Function and Pointer

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();


           printf ("\n Enter a Number : ");

           scanf ("%d",&a);


           printf ("\n The Sum of first %d is : %d",a,f);



/* 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;


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles