Why do we not use const more often? - c

It is common to see the keyword const with pointers :
void function(const char *string)
{
const char *other_string = "some string";
}
But why do not we use const every time we declare a variable that we will not change ? It is rare to see :
void function(const int i)
{
const double j = 1.2;
// i and j will not be changed in this function
}
I am trying to understand why we do not use const more often, is it always a good thing to use it when we can, or not ?
This post seems to answer YES, but in reality this doest not seem to be the case ...

In most cases it no longer makes a difference.
Often enough the compiler will be able to deduce that the variable is actually read only, and treat it as a constant during optimization.
Either way, you usually use const consequently on things like const char *string in order to avoid accidentally modifying the parameter.
Since all parameters are passed by value, this isn't something which can't happen for an integer. Only for pointers the pointer itself is the value.
Actually, const char *string isn't fully constant either yet. Only the chars the pointer is pointing to is, but the pointer as a variable isn't. It would only become when specifying it as const char * const string. Now the string variable is completely constant for the scope of the function.

In the case you give, I would always say
void function(const int i)
in a situation where the role of i is to parameterise the behaviour of the function -- which is almost always. If I change i in the body of the function, I have either made an error, or written something which another person will find hard to understand later.
Intentionally modifying the value of i in the function isn't as "dangerous" as modifying a entity through its pointer -- it won't create side-effects outside the function. I guess that's why most developers don't feel the pressure to define primitive paramters as const. I maintain, however, that it is a sensible thing to do, if one cares about long-term maintenance.

In your second example, the parameter is passed by value, making it const basicly has no meaning. const is most handy when passing parameters by reference.
There is another problem with const known as "const poisoning". Consider the following:
int foo(char * str, int n)
{
...
bar(str);
...
}
If we make str to be const, we must then ensure that bar also takes a const etc. (which can affect multiple files and modules). This is especially painful if you're editing old and inconsistent code (not always the case, but should be considered).

Related

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

This question already has answers here:
Const correctness for value parameters
(6 answers)
Closed 6 years ago.
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)?
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.
It's unnecessary to use const for a value parameter, but it has its value if what you want is to guarantee the code does what you intend.
Here there's an answer with some example of use cases
It's the same thing as declaring any constant variable
const int size = some_other_variable + 5;
It is a good programming practice to declare variables as const if you know their values will not change. That way from declaration you can avoid that someone accidentally changes their value further down the function.
It means that an implementer of the function cannot change the value of the input parameter a that the function receives by value.
It can lead to increased program stability.
(Personally I dislike the style as I find it too verbose).
If you do adopt this style, then note well that you only need to put the const in the parameter list of the function definition, you don't need it in the declaration.
It's useful mostly for purposes of self-documenting your code.
For future people looking through your source code, the const serves to emphasize your intent (that none of the code in foo() should attempt to modify a).

Declaring a pointer to const or a const pointer to const as a formal parameter

I was recently making some adjustments to code wherein I had to change a formal parameter in a function. Originally, the parameter was similar to the following (note, the structure was typedef'd earlier):
static MySpecialStructure my_special_structure;
static unsigned char char_being_passed; // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure; // Passed to function elsewhere.
int myFunction (MySpecialStructure * p_structure, unsigned char useful_char)
{
...
}
The change was made because I could define and initialize my_special_structure before compile time and myFunction never changed the value of it. This led to the following change:
static const MySpecialStructure my_special_structure;
static unsigned char char_being_passed; // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure; // Passed to function elsewhere.
int myFunction (const MySpecialStructure * p_structure, unsigned char useful_char)
{
...
}
I also noticed that when I ran Lint on my program that there were several Info 818's referencing a number of different functions. The info stated that "Pointer parameter 'x' (line 253) could be declared as pointing to const".
Now, I have two questions in regards to the above. First, in regards to the above code, since neither the pointer nor the variables within MySpecialStructure is changed within the function, is it beneficial to declare the pointer as constant as well? e.g. -
int myFunction (const MySpecialStructure * const p_structure, unsigned char useful_char)
My second question is in regards to the Lint information. Are there any benefits or drawbacks to declaring pointers as a constant formal parameter if the function is not changing its value... even if what you are passing to the function is never declared as a constant? e.g. -
static unsigned char my_char;
static unsigned char * p_my_char;
p_my_char = &my_char;
int myFunction (const unsigned char * p_char)
{
...
}
Thanks for your help!
Edited for clarification -
What are the advantages of declaring a pointer to const or a const pointer to const- as a formal parameter? I know that I can do it, but why would I want to... particularly in the case where the pointer being passed and the data it is pointing to are not declared constant?
What are the advantages of declaring a pointer as a const - as a formal parameter? I know that I can do it, but why would I want to... particularly in the case where the pointer being passed and the data it is pointing to are not declared constant?
I assumed you meant a pointer to const.
By have a pointer to const as a parameter, the advantage is you document the API by telling the programmer your function does not modify the object pointed by the pointer.
For example look at memcpy prototype:
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);
It tells the programmer the object pointed to by s2 will not be modified through memcpy call.
It also provides compiler enforced documentation as the implementation will issue a diagnostic if you modify a pointee from a pointer to const.
const also allows to indicate users of your function that you won't modify this parameter behind their back
If you declare a formal parameter as const, the compiler can check that your code does not attempt to modify that parameter, yielding better software quality.
Const correctness is a wonderful thing. For one, it lets the compiler help keep you from making mistakes. An obvious simple case is assigning when you meant to compare. In that instance, if the pointer is const, the compiler will give you an error. Google 'const correctness' and you'll find many resources on the benefits of it.
For your first question, if you are damn sure of not modifying either the pointer or the variable it points to, you can by all means go ahead and make both of them constant!
Now, for your Qn as to why declare a formal pointer parameter as const even though the passed pointer is not constant, A typical use case is library function printf(). printf is supposed to accept const char * but the compiler doesn't complain even if you pass a char* to it. In such a case, it makes sense that printf() doesn't not build upon the user's mistake and alter user's data inadvertantly! Its like printf() clearly telling- Whether you pass a const char * or char*, dont worry, I still wont modify your data!
For your second question, const pointers find excellent application in the embedded world where we generally write to a memory address directly. Here is the detailed explanation
Well, what are the advantages of declaring anything as a const while you have the option to not to do so? After all, if you don't touch it, it doesn't matter if it's const or not. This provides some safety checks that the compiler can do for you, and it gives some information of the function interface. For example, you can safely pass a string literal to a function that expects a const char *, but you need to be careful if the parameter is declared as just a char *.

Is it true that (const T v) is never necessary in C?

For example:
void func(const int i);
Here,the const is unnecessary since all parameters are passed by value(including pointers).
Is that true?
All parameters in C are indeed passed by value, which means that the actual argument will not change regardless of whether you include that const or not.
However, that does not mean that const here is "never necessary". Whether it is necessary or unnecessary depends on what you want to achieve.
If you want to prevent any attempts to modify the parameter inside the function, then the const is necessary, of course.
There is a fairly popular (and pretty reasonable) coding guideline that says that function parameters should never be modified inside the function, i.e. that at any point of function's execution all parameters must retain their original values. Under this guideline it would actually make perfect sense to always include that const in all parameter declarations.
const is just used by the precompiler, to notice about errors...
Note that this is perfectly valid:
void foo( const char * bar )
{
char * baz = ( char * )bar;
baz++;
}
So it's never necessary, but it just makes the code more readable, and informs you the pointer should never change...

const read only local copies

gcc 4.4.4 c89
I am just wondering is it worth passing a const into a function.
i.e.
void do_something(const char *dest, const int size)
The size is a read-only so I don't want to change it. However, some developers never have this as const has it is a local copy that is being used. The pointer is const as you can change the value in the calling routine.
I always have a const on read-only local copies, as it confirms to anyone reading my code that it is a read-only variable. And also, when coding I don't make the mistake of changing it without realizing.
Many thanks for any suggestions,
People's opinion differ on this. I know some perfectly capable developers who write that const for any parameter that should not be changed locally in the function. Logically that is just consequent application of the const-correctness principle.
Whatever you do, however, you should omit the const in the function declaration in the header. The const should be part only in the function definition. C (and C++, too) has rules that make this compatible (i.e a const for a value parameter is ignored (when it affects the parameter only at its toplevel) for pure function declarations that don't have a body). The rationale is that such a const will not change anything with regard to the caller, and is thus an implementation detail of the called function.
This does not hold for your first parameter. Any capable developer i know will put that const there, because it's making an important guarantee to the caller of your function (that it won't change the data pointed to of what is passed in). The name of your parameter, however, seems a bit odd, because it indicates that the function does need to write into what is pointed to.
Notice that to be consequent, you would have to make the first parameter itself const too, like you did with the second parameter. Thus this would become (renaming it to "source" too, to avoid confusion).
void do_something(const char * const source, const int size)
Personally, I like putting const on as many variables as possible – I rarely change the value of a variable once assigned. (One notable exception are of course loop counters/iterators.)
At the very least, this significantly improves debuggability because it ensures that values cannot be changed. This makes tracking the state of the execution much easier. It also improves readability because it signals the intent of working with immutable values.
Consequently, I do the same for function parameters. After all, they behave like normal variables inside the function.
On the other hand, this confuses the hell out of many other programmers so in most collaborative projects I refrain from doing this; it would break consistency and be counter-productive.
The so called "const correctness" is very important especially if you are creating some module (dll for example) where other people will use it. It makes it much easier to understand the purpose of the function and helps prevent some odd bugs (among other things). So yes, i would definetly suggest using the const modifier where applicable.
EDIT: now looking closely at the function header, it seems that "dest" is something which the function has to change. Then declaring it as const seems odd.
In my opinion there is no point in declaring const on anything else than a pointed area. Scalar parameters (and even pointers) are local copies with the exact same constraints as other local variables. They are in fact local variables and it's sometime appropriate to use them and modify them which may avoid unecessary copies of their values.
char * strcat(char *d, const char *s)
{
char *p = d;
while(*p) p++;
while(*s) *p++ = *s++;
*p = 0;
return d;
}
char * strcat(char *d, const char *s)
{
char *p = d;
const char *s2 = s;
while(*p) p++;
while(*s2) *p++ = *s2++;
*p = 0;
return d;
}
Is the second variant really better? I don't think so.
When using the old K&R syntax it's more obvious that they are local variables of the function.
char * strcat(d, s)
char *d;
const char *s;
{
...

Should useless type qualifiers on return types be used, for clarity?

Our static analysis tool complains about a "useless type qualifier on return type" when we have prototypes in header files such as:
const int foo();
We defined it this way because the function is returning a constant that will never change, thinking that the API seemed clearer with const in place.
I feel like this is similar to explicitly initializing global variables to zero for clarity, even though the C standard already states that all globals will be initialized to zero if not explicitly initialized. At the end of the day, it really doesn't matter. (But the static analysis tool doesn't complain about that.)
My question is, is there any reason that this could cause a problem? Should we ignore the errors generated by the tool, or should we placate the tool at the possible cost of a less clear and consistent API? (It returns other const char* constants that the tool doesn't have a problem with.)
It's usually better for your code to describe as accurately as possible what's going on. You're getting this warning because the const in const int foo(); is basically meaningless. The API only seems clearer if you don't know what the const keyword means. Don't overload meaning like that; static is bad enough as it is, and there's no reason to add the potential for more confusion.
const char * means something different than const int does, which is why your tool doesn't complain about it. The former is a pointer to a constant string, meaning any code calling the function returning that type shouldn't try to modify the contents of the string (it might be in ROM for example). In the latter case, the system has no way to enforce that you not make changes to the returned int, so the qualifier is meaningless. A closer parallel to the return types would be:
const int foo();
char * const foo2();
which will both cause your static analysis to give the warning - adding a const qualifier to a return value is a meaningless operation. It only makes sense when you have a a reference parameter (or return type), like your const char * example.
In fact, I just made a little test program, and GCC even explicitly warns about this problem:
test.c:6: warning: type qualifiers ignored on function return type
So it's not just your static analysis program that's complaining.
You can use a different technique to illustrate your intent without making the tools unhappy.
#define CONST_RETURN
CONST_RETURN int foo();
You don't have a problem with const char * because that's declaring a pointer to constant chars, not a constant pointer.
Ignoring the const for now, foo() returns a value. You can do
int x = foo();
and assign the value returned by foo() to the variable x, in much the same way you can do
int x = 42;
to assign the value 42 to variable x.
But you cannot change the 42 ... or the value returned by foo(). Saying that the value returned from foo() cannot be changed, by applying the const keyword to the type of foo() accomplishes nothing.
Values cannot be const (or restrict, or volatile). Only objects can have type qualifiers.
Contrast with
const char *foo();
In this case, foo() returns a pointer to an object. The object pointed to by the value returned can be qualified const.
The int is returned by copy. It may be a copy of a const, but when it is assigned to something else, that something by virtue of the fact that it was assignable, cannot by definition be a const.
The keyword const has specific semantics within the language, whereas here you are misusing it as essentially a comment. Rather than adding clarity, it rather suggests a misunderstanding of the language semantics.
const int foo() is very different from const char* foo(). const char* foo() returns an array (usually a string) whose content is not allowed to change. Think about the difference between:
const char* a = "Hello World";
and
const int b = 1;
a is still a variable and can be assigned to other strings that can't change whereas b is not a variable. So
const char* foo();
const char* a = "Hello World\n";
a = foo();
is allowed but
const int bar();
const int b = 0;
b = bar();
is not allowed, even with the const declaration of bar().
Yes. I would advise writing code "explicitly", because it makes it clear to anyone (including yourself) when reading the code what you meant. You are writing code for other programmers to read, not to please the whims of the compiler and static analysis tools!
(However, you do have to be careful that any such "unnecessary code" does not cause different code to be generated!)
Some examples of explicit coding improving readability/maintainability:
I place brackets around portions of arithmetic expressions to explicitly specify what I want to happen. This makes it clear to any reader what I meant, and saves me having to worry about (or make ay mistakes with) precedence rules:
int a = b + c * d / e + f; // Hard to read- need to know precedence
int a = b + ((c * d) / e) + f; // Easy to read- clear explicit calculations
In C++, if you override a virtual function, then in the derived class you can declare it without mentioning "virtual" at all. Anyone reading the code can't tell that it's a virtual function, which can be disastrously misleading! However you can safely use the virtual keyword: virtual int MyFunc() and this makes it clear to anyone reading your class header that this method is virtual. (This "C++ syntax bug" is fixed in C# by requiring the use of the "override" keyword in this case - more proof if anyone needed it that missing out the "unnecessary virtual" is a really bad idea)
These are both clear examples where adding "unnecessary" code will make the code more readable and less prone to bugs.

Resources