Question:
what's the point of using 'const' variables in C++?
anonymous
2013-05-18 05:43:28 UTC
consider the following two decharations:-
1. const int size=3;
2. int size=3;
according to the book (oop with C++ by sir e. balaguruswami), in case 1, the value of size cannot be changed by the rest of the code, while in case 2, it can be changed. But what's the point anyway? If we don't want the value of 'size' to be altered by the rest of the program, we can simply write code which won't try to change the value of 'size'. On the other hand, if we write code such that the value of 'size' changes with time, the 'const' qualifier will not prevent it, right? All it can do is generate a compile time error.
Please explain if u can, my university semesters are starting from the 22nd and i am so screwedd. Didn't study anything all the year and now i'm in deep deep trouble :(
C++ is supposed to be one of the easier papers. If this is my condition in C++, then u can figure how screwed i am in the other papers. DBMS, Numerical Methods, OS designing concepts, software project management... I'm so screwed. Please pray for me :(
if possible, please suggest how to finish this up a little faster so that i can at least pass the exams. The way i am now, i will definitely fail and get kicked out of college :(
please please please help :(
Four answers:
husoski
2013-05-18 07:54:36 UTC
The compile time error prevents the program from running because no code is generated, so there is a point. It's not for security, though. There is a legal C++ syntax to override that const declaration. There's also a "goto" statement in C++. Neither should be used often enough to say you actually use them.



There are a couple of related uses of const. The simplest is the case of a const variable.



1. If example 1 is a plain variable, then it's main purpose is to give a name to use instead of the number 3 to help make the meaning of code clearer to the reader and also make maintenance of code easier for the writer, and still let the compiler fully optimize the generated code knowing that any use of that "size" variable is really just an int value of 3 and can generate code to take advantage of that fact. When the programmer wants to change that size value, he does so in just one place instead of looking for all uses of "3" that might be a size.



There's the point. Use of const allows the programmer to code safely and efficiently (single point of maintenance for that "size" value) and still allows the compiler to generate high-quality code.



2. Arguments to a function can be declared as const. This is particularly helpful with reference and pointer arguments. C++ function calls normally pass non-array arguments by value. The function gets a copy of the argument value and never sees the original arguments used in the function call. This is a problem in at least two situations.



If the called program needs to make changes to the object, any changes it makes to a value argument are lost when the function returns and the temporary copy of the argument value is discarded. Also, if the argument is a very large object or has some internal state (like a file object) that prevents it from being copied to a temporary value, then it may be impractical or impossible to make the copy on every function call that uses that object as an argument.



A reference argument solves both problems by passing a reference to the original argument instead of a copy. A const reference says that a reference argument is used for input only and is not changed by the function call. Pointer and array arguments can be declared const for the same reason.



3. Member variables can be declared as const. The values of these don't change over the full lifetime of the object. Only the constructor can write to such a member. These aren't used very often.



4. Static member variables can be declared as const, too. These behave like regular const variables above and are used for the same reason that symbols are more intelligible than numbers. There's a different syntax for intializing non integral types, though, and they are part of a class namespace rather than an ordinary namespace like "std" or the unnamed global namespace.



5. Member functions ("methods") in a class can be declared as const to say that they do. This allows them to be called on object that were passed a const reference or pointer. For example, if s is a (const string&) argument, then using s.length() to get the length of the string is okay because length() is declared as const. Calling s.clear() to reset s to an empty string is NOT okay.



Someone else said it already, but I'll repeat it. That's the sort of thing that lets you find errors at compile time instead of at runtime, and that's a Real Good Idea.
_Object
2013-05-18 06:36:52 UTC
The const modifier has pretty simple but important uses:

First, by declaring something 'const' we enforce our promise to not alter an object at run time, while providing an powerful complex-object safe modifier which can protect both integral and custom types. Changing a const object causes an error; which is good. Otherwise you'll be searching for logic errors, which isn't!

Secondly, const provides an all too important declaration of intent -- there should be a big difference between passing 'const Object & Elem' and passing 'Object & Elem' to a method, the second should be expected to alter Elem, while the first proves that no changes will be made to the first object. Like an operator=(), the function shouldn't change the RHS value, because that wouldn't be intuitive (but not illegal).

The single most important (in my opinion) consideration in C++ is writing readable code. This means unit tests as documentation, short methods, adequate and descriptive names, a bunch of other stuff, and not least proper use of the 'const' modifier.

Use it; even aside from readability, when you're dealing with user-defined operators it becomes a lot easier to accidentally alter some object/value... I've done this and the outcome was not pretty.

Best of luck on your exams!

Should've studied (But I wouldn't have either (: )



tl;dr Keeps code simple and readable, and improves safety.
Chris
2013-05-18 06:00:20 UTC
To quote stackoverflow:



const is a tool which you should use in pursuit of a very important C++ concept:



Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.



Even though it doesn't change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do.





My interpretation: sure, we can write code that doesn't try to change size, but using const makes sure we actually don't.
jplatt39
2013-05-18 06:20:43 UTC
Ever hear of hackers crackers and security? It's not perfect but the constant keyword is one more way to keep variables from being changed by inappropriate sources. Got that? It's why objects default to private members.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...