c++ - Why would you use the keyword const if you already know variable should be constant? -


many of books reading use keyword const when value of variable should not modified. apart specifying readers of code may cause errors if modify variable (you can use comments this), why need keyword part of programming language? seems me if don't want variable modified, don't.

could clarify me?

apart specifying readers of code may cause errors if modify variable(you can use comments this)

not "may"; will cause errors in program.

  • a c++ compiler enforce compilation failures , diagnostic messages ("compiler errors"), no need comments;
  • a c compiler enforce for part, though standard library has holes legacy, such strchr, , has rather lenient implicit conversion rules can allow drop constness without realising quite easily. however, because got successful compilation doesn't mean don't have errors; unfortunately, does mean errors can subtle bugs in program, big, spectacular crashes.

either way, program guaranteed contain error inside it.

it seems me if don't want variable modified, don't.

well that's , good, nobody's perfect. programmers make mistakes. allows compiler — never makes mistakes (at least, not usually) — point them out you.

it's of particular use when you're using data variable many, many lines of code away created. further away is, easier modify without realising not supposed to. large, complex code bases must.

you new measure of provability, correctness , stability in code base, huge chunk off possible causes of subtle , nasty bugs. there vast optimisation opportunities compiler (in cases) when knows value won't change after compilation.

we list advantages day but, really, won't grok until you've worked on such codebase.

in fact, in perfect world, all variables const default, , need declare them keyword mutable able change them. c++ backwards.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -