Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does const in void foo(const int a) do? [duplicate]

Tags:

c

constants

I do understand the meaning of const for pointers or structures that have to be passed by reference to a function. However in the example:

void foo(const int a);

the variable a is passed on the stack. There is no harm to the caller to modify the content of the stack so const looks pretty useless in this situation.

Furthermore, if I cannot modify a, I can still make a copy of a and change this copy:

void foo(const int a)
{
   int b = a;
   b++;
}

In which situation does the const keyword will be useful when applied to a scalar function argument (not a pointer)?

like image 704
nowox Avatar asked Apr 12 '16 14:04

nowox


1 Answers

Code like void foo(const int a) is not really meaningful, nor is it "const correctness" as such.

Sometimes overly pedantic programmers get the weird idea that they need to declare common parameters as const just because a function doesn't modify the actual parameter. But most often, functions do not.

The point is, the variable is a copy of the original, so what your function does with it doesn't matter the slightest!

So this is not even a way of writing self-documenting code, because all it does is to tell the caller what's going on internally inside your function. The caller doesn't care and shouldn't care.

like image 149
Lundin Avatar answered Sep 24 '22 03:09

Lundin