Why would you use the keyword const if you already

2019-02-02 01:50发布

Many of the books that I am reading use keyword const when the value of a variable should not be modified. Apart from specifying to readers of the code that you may cause errors if you modify this variable (you can use comments to do this), why would you need that keyword to be a part of any programming language? It seems to me that if you don't want a variable modified, simply don't.

Could someone clarify this for me?

11条回答
够拽才男人
2楼-- · 2019-02-02 02:11

Keyword const is very useful for teams and long term projects. I'll give you few examples, those should explain value of const keyword.

Lets say now I'm creating lib that will be used for further projects. So it means that code written today needs to be trusted after a few years, in such a period of time probable I will forget which variable shouldn't be modified (colleagues even do not know what can be modified and what cannot). So this short example explains why to use const.

Talking about comments, when the deadline is coming and there is plenty of stuff which still not working comments on every function would be just a waste of time. However in some cases comments is a must, because of the first problem (deadline) comments may be not read, because most them are useless but important comments will be skipped too. So it is better to use const keyword which gives compilation error and points you into the problem then writing and reading lot of comments.

查看更多
祖国的老花朵
3楼-- · 2019-02-02 02:12

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 some kind of list of nodes. First, without even knowing the names of the functions we can see immediately which functions change our list in some way, and which ones don't. The const functions, like in the standard libraries, are ones that do not change your data, and won't allow you to change your data with them. The C compiler tries to keep the const-ness of the pointers enforced to the data you are passing to the functions. So in this case I can be reasonably sure that comparing two lists isn't the function that is mangling them when I do my runtime debugging, as I have protected myself against accidental modifications to my data. ;)

查看更多
SAY GOODBYE
4楼-- · 2019-02-02 02:21

Your compiler can make big optimizations, knowing that a variable won't be changed: instead of storing it in memory, it's directly written into the executable opcode.

example: you have a and b, you want to add them, you make a + b. If you declare a to be const and of value 3, the program will make 3 + b instead, which will save memory and cycles becayse it won't need to retrieve the a value.

The problem is that your compiler cannot know in advance if variables are constant or not, of course it could analyze the whole code and check whether you modified such variables, but it's not 100% sure, since future code can also modify it.

查看更多
萌系小妹纸
5楼-- · 2019-02-02 02:23

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

查看更多
狗以群分
6楼-- · 2019-02-02 02:24

Apart from specifying to readers of the code that you may cause errors if you modify this variable(you can use comments to do this)

Not "may"; will cause errors in your program.

  • A C++ compiler will enforce it with compilation failures and diagnostic messages ("compiler errors"), with no need for comments;
  • A C compiler will enforce it for the most part, though its standard library has holes thanks to legacy, such as strchr, and it has some rather lenient implicit conversion rules that can allow you to drop constness without realising it quite easily. However, just because you got a successful compilation doesn't mean that you don't have errors; unfortunately, it does mean that the errors can be subtle bugs in your program, as well as big, spectacular crashes.

Either way, your program is guaranteed to contain an error inside it.

It seems to me that if you don't want a variable modified, simply don't.

Well that's all well and good, but nobody's perfect. Programmers make mistakes. This allows the compiler — which never makes mistakes (at least, not usually) — to point them out to you.

It's of particular use when you're using some data variable many, many lines of code away from where it was created. The further away it is, the easier it is to modify it without realising that you were not supposed to. For large, complex code bases it is simply a must.

You get a new measure of provability, correctness and stability in your code base, as well as a huge chunk off possible causes of really subtle and nasty bugs. There are also vast optimisation opportunities for your compiler (in some cases) when it knows that some value won't change after compilation.

We could list the advantages all day but, really, you won't fully grok it until you've worked on such a codebase.

In fact, in a perfect world, all variables would be const by default, and you would need to declare them with the keyword mutable to be able to change them. C++ is backwards.

查看更多
不美不萌又怎样
7楼-- · 2019-02-02 02:25

This is a hard question because IMO it is based on beliefs. One of those beliefs is that you can protect your code against some kind of changes just adding more code. Of course, that extra code is used by the compiler to check everything is alright.

I think that is not always right, you cannot protect your code against yourself or your development team just adding keywords, in fact there are lots of languages which don´t have any const, public, private, protected, internal, int, float, double keywords and that doesn´t mean they are not good languages.

The same happens with some code patterns, why do people wasted so much time discussing about Singletons!? If you want to have only one instance, the only thing you have to do is to create just one instance, that´s all. The same mindset is everywhere around, take a look at the defensive programming articles published 10 years ago, once more the idea of protecting code with code.

In some point you have to decide where you want to set the responsibilities, on the developers' hands or on the compilers' ones. However, neither the compiler nor any other tool can save the code against the developers and for that reason lots of keywords are worthless or just a way to communicate something to other developers.

查看更多
登录 后发表回答