Similar to this question, what are the pro/cons to using const local variables like in this answer?
-
2@Jay: Function parameters are local variables.Benjamin Lindley– Benjamin Lindley2012-01-05 02:03:20 +00:00Commented Jan 5, 2012 at 2:03
-
1As it stands, there is no content in this question. Please could you write some words.Lightness Races in Orbit– Lightness Races in Orbit2012-01-05 02:08:03 +00:00Commented Jan 5, 2012 at 2:08
-
1@Jay : The converse doesn't need to be true, that's completely irrelevant.ildjarn– ildjarn2012-01-05 02:13:45 +00:00Commented Jan 5, 2012 at 2:13
-
1@ildjarn I disagree. If the other question was about local variables, and my question was about function parameters, then my question would be pointless. But it is the other way around, so my question is different.user542687– user5426872012-01-05 02:16:42 +00:00Commented Jan 5, 2012 at 2:16
-
1@Farhad: References and pointers are whole different animals, we're talking about passing by value. But still, what I said is true of them also, the parameter is not the thing pointed to or referred to, but the pointer or reference itself, which is in fact local.Benjamin Lindley– Benjamin Lindley2012-01-05 02:28:06 +00:00Commented Jan 5, 2012 at 2:28
1 Answer
Personally, I like to use const for any declared object (I'm not sure the word "variable" applies) unless I'm actually going to modify it. It documents to the reader that the value of the object is always going to be whatever it was initialized to, which can make the code easier to follow and analyze.
(It can also help the compiler in some cases, but most compilers, when invoked in optimizing mode, are smart enough to notice that the object is never modified. And if you invoke the compiler in non-optimizing mode, you're telling it that you don't care much about performance.)
In fact, if I were going to design my own language, all declared objects would be const (read-only) by default unless you explicitly mark them as modifiable.