Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const-correctness in C

Apparently it's good practice to use const unless something is meant to be mutable, but how far do you go? If I have an array of strings, should my function signature include this?

char const * const * const my_strings

I'm not going to be modifying it whatsoever, so it's a constant pointer to the first element of an array of constant pointers to the first elements of arrays of constant characters. That's a mouthful, and the code is nearly unreadable. All this is a simple data structure like argv.

I feel as though const should be default and there should be a mutable keyword.

Do you generally just one of those consts? What's the point of that then, if you can still easily change it by dereferencing more or less?

like image 453
mk12 Avatar asked Aug 09 '12 00:08

mk12


1 Answers

I would generally use two of the three consts:

const char *const *my_strings;

Sometimes I would use all three, but in my opinion the last one is the least important. It only helps analyze the code that uses the variable my_strings, whereas the other two help analyze code that has any pointer to the array pointed to by my_strings, or to the strings pointed to by the elements of that array. That's generally more code, in several different places (for example the caller of a function and the function itself), and hence a harder task.

The code that uses the variable itself is limited to the scope of my_strings, so if that's an automatic variable (including a function parameter) then it is well-contained and an easier task. The help provided by marking it const might still be appreciated, but it's less important.

I would also say that if char const * const * const my_strings is "nearly unreadable", then that will change when you have more practice at reading C, and it's better to get that practice than to change the code. There's some value in writing C code that can be easily read by novices, but not as much value as there is in getting some work done ;-)

You could use typedefs to make the variable definition shorter, at the cost of introducing an indirection that will annoy many C programmers:

typedef char const *ro_strptr;
ro_strptr const *my_strings;

For whatever reasons, C programmers often want to see as much as possible of a type in one place. Only when the type gets genuinely complicated (pointer-to-function types) can you use a typedef solely to abbreviate, without half-expecting that somebody will complain about it.

like image 189
2 revs Avatar answered Dec 01 '22 22:12

2 revs