Why use the const keyword if you already know that a variable must be constant?

Many of the books I read use the const keyword when the value of a variable should not change. Besides telling readers code that can cause errors if you change this variable (you can use comments for this), why do you need this keyword to be part of any programming language? It seems to me that if you do not want the variable to be changed, just do not do it.

Can anyone clarify this for me?

+66
c ++ c keyword const
Aug 10 '13 at 0:37
source share
11 answers

Besides instructing readers to code that might cause errors if you change this variable (you can use comments for this)

Can not"; will lead to errors in your program.

  • The C ++ compiler will use it with compilation errors and diagnostic messages ("compiler errors"), without comment;
  • The AC compiler will use it for the most part, although its standard library has openings thanks to a legacy such as strchr , and has some pretty mild implicit conversion rules that can allow you to discard const without implementing it quite easily. However, just because you received a successful compilation does not mean that you have no errors; Unfortunately, this means that errors can be small errors in your program, as well as large impressive crashes.

In any case, your program is guaranteed to contain an error inside it.

It seems to me that if you do not want the variable to be changed, just do not do it.

It’s good that everything is good and good, but no one is perfect. Programmers are wrong. This allows the compiler - which never makes mistakes (at least not normally); point them to you.

This is especially useful if you are using some kind of data variable, many, many lines of code are where they were created. The further you go, the easier it is to change it without realizing what you should not. For large, complex codebases, this is simply a must.

In your code base you get a new measure of provability , correctness and stability , as well as a huge fragment of the possible causes of really subtle and unpleasant errors. For your compiler (in some cases) there are ample opportunities for optimization when he knows that after compilation some value will not change.

We could list the benefits all day long, but really, you won’t fully test them until you work on such a codebase.

In fact, in an ideal world, all variables will be const by default , and you will need to declare them with the mutable keyword in order to be able to change them. C ++ - back.

+96
Aug 10 '13 at 0:41
source share

At least in C ++, const uses some functions, in addition to documenting your intentions to other programmers.

const can also tell the compiler some things. For example, a function that accepts a link, for example: void f(T &t); , cannot accept a temporary object as its parameter. To do this, you need to assign a link to const , for example: void f(T const &t) .

Similarly, to call a member function in a const object, the member function must be const qualified as: void T::foo() const {} .

In the embedded system, const can mean even more, possibly telling the compiler where to find the given object (by placing it in ROM or RAM). const itself is not necessarily enough to say that it "puts this object in ROM", but it is still often a prerequisite.

Similarly (under C ++ 11) const tells the compiler about thread safety .

Now, it is undoubtedly true that you could define some other language that (in other ways) had some similarities with C or C ++, which did not use const these ways. The result would be a completely different language. Unaware of your intentions, it is impossible to say how this will turn out, but it may turn out to be closer to Java or C # (for a few examples), both of which are somewhat similar to C and C ++ in some way, but not in this particular one. (i.e. don't use const like C and C ++ do).

+40
Aug 10 '13 at 0:52
source share

Besides the usual programming considerations already discussed in other answers, one thing that concerns me is the attitude:

It seems to me that if you do not want the variable to be changed, simply not.

The general rule is that 20% of the cost of writing code is spent at the development stage. Another 80% is spent on the life of the code, updating it, saving it, etc. This means that many other people will work on your code except you.

Time spent during development that avoids problems over the years is a good investment. These efforts include: writing comments; defining constants that are constants; and write explicit code that does not rely on obscure language constructs.

Also, @worlboss, I hear quite a lot of intolerance. As some others comment, carbon units make mistakes, and everything a silicon block can do to help avoid mistakes is appreciated.

+36
Aug 10 '13 at 1:29 on
source share

It tells the compiler that the variable should not be changed, so if someone writes code that modifies it, the compiler puts it as an error.

+21
Aug 10 '13 at 0:39
source share

Two reasons:

  • compiler related documentation
  • compiler optimization

Here is a good description from Ian Lance Taylor (who worked on gcc and gold linker):

The first value of const has a real impact on the program. A variable declared by const can be compiled differently than a variable that is not declared by const.

The second value of const, on the other hand, is, in fact, documentation related to the compiler. The compiler will throw an error if an attempt is made to change the value using a pointer with a const sign, but declaring such a pointer will not change the generated code.

+17
Aug 10 '13 at 0:59
source share

Here is a simple C example:

 void PrintList(const struct List *l); void SortList(struct List *l); int CmpList(const struct List *a, const struct List *b); void AppendList(struct List *l, struct List *m); void PushList(struct List *l, struct ListNode *n); void PopList(struct List *l, struct ListNode *n); 

Here we have a small set of functions that work with a list of nodes. First, even without knowing the names of the functions, we immediately see which functions somehow change our list and which do not. The const functions, as in standard libraries, are those that do not change your data, and will not allow you to change your data. The C compiler tries to preserve the const -ness of pointers bound to the data you pass into the function. Therefore, in this case, I can be sure that comparing the two lists is not a function that changes them when I perform debugging at runtime, since I protected myself from accidentally changing my data .;)

+6
Aug 10 '13 at 12:25
source share

Your compiler can make great optimizations, knowing that the variable will not be changed: instead of storing it in memory, it is directly written to the executable code of the operation.

Example

: you have a and b, you want to add them, you do + b. If you declare a constant and a value of 3, the program will do 3 + b instead, which will save memory and cycles, because you do not need to extract the value.

The problem is that your compiler cannot know in advance if the variables are constant or not, of course, he could analyze the whole code and check if you have changed such variables, but this is not 100% certain, since the future code also can change it.

+5
Aug 10 '13 at
source share

The const keyword is very useful for teams and long-term projects. I will give a few examples that should explain the meaning of the const keyword.

Let's now say that I am creating a lib that will be used for future projects. Thus, this means that the code written today should be trusted in a few years, for such a period of time, I will probably forget which variable should not be changed (colleagues do not even know what can be changed and what cannot). So this short example explains why to use const .

Speaking of comments, when the deadline expires, and there are many things that still don't work, comments on each function will be just a waste of time. However, in some cases, comments are mandatory because the first problem (deadline) may not be read, because most of them are useless, but important comments will also be skipped. Therefore, it is better to use the const keyword, which gives a compilation error and indicates a problem, and then write and read a lot of comments.

+4
Aug 12 '13 at 12:30
source share

This is a difficult question because IMO is belief based. One of these beliefs is that you can protect your code from any changes by simply adding more code. Of course, this additional code is used by the compiler to check if everything is in order.

I think this is not always right, you cannot protect your code from yourself or your development team, simply adding keywords, in fact there are many languages ​​that have no constants, open, closed, protected, internal, int, float, double keywords and this does not mean that they are not good languages.

The same thing happens with some code templates, why do people waste so much time discussing about Singletons !? If you want to have only one instance, the only thing you need to do is create only one instance, that's all. The same thinking is everywhere, take a look at the security programming articles published 10 years ago, once again the idea of ​​protecting code with code.

At some point, you need to decide where you want to set responsibilities, on the hands of developers or on compilers. However, neither the compiler nor any other tool can save code against developers, and for this reason many keywords are useless or just a way to tell something to other developers.

+2
Aug 14 '13 at 1:32
source share

Constant variables just let you write more readable code.

The greatest use for const almost all languages ​​is to allow us to use names to indicate constant values, so you can tell others, in a free language, what this name refers to, without requiring the distribution of comments in your code and saving readers time and effort in order to find out the type of parameters and features of the parameters. Of course, you also win if your constant value is reused in your code. Well, such code might be more readable:

 processPages(LETTER_PAPER_WIDTH, LETTER_PAPER_HEIGHT); 

... than this:

 processPages(215.9, 279.4); // 8.5 x 11 Inches in millimeters for Letter Papers 

In the above example, you need to understand that each parameter, its unit and type is for interpreting the values, and you still need to check it for a comment, because an excess comment like this (those comments that reproduce what is encoded) is not reliable and such a useful comment (this is a bad comment according to Robert Martin in Pure Code: http://goo.gl/5EyY ).

+1
Aug 13 '13 at 21:08
source share

Consider a scenario in which you use the same constants many times in your entire project, and you hard code it in all places. Now, unexpectedly, you need to change the constant value to another value, so it will randomly make changes in all places.

Therefore, I believe that making the code more convenient for maintenance will definitely be one of the reasons.

-2
Aug 10 '13 at 5:51
source share



All Articles