What is the benefit of the const keyword in programming? [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Sell me on using const correctness
I'm eager to know the answer. [to "What is the benefit of const keyword in programming?"]

const indicates that the value assigned to the variable cannot change. If you try to change the value you should get a compiler error.

The const keyword can declare a read only variable.
Using const parameters to a method tells you the method will not change the parameter.
A const method tells you that the method will not alter a class's member variables (but can change member variables marked as mutable)
You can also declare const pointers, better described here

What is the benefit of const keyword in programming?
Specifying a variable as const states that the variable's value should never change after the initial assignment. This allows the compiler to perform additional tests at compilation (validating your code).
For example, if a const function changes a (non-mutable) member in an object, the compiler will yield an error.

Benefit: You get more compile time checks to ensure that you're not changing data that shouldn't be changed.
Cost: You have to use it everywhere. If you need to, you can cast your way out of it, nullifying the benefits.
Getting usage right can be tricky with pointers. Is the pointer itself const, or the data it refers to? This is also the most common usage I've seen: you want to point to immutable memory.

Related

Does adding the C++ prefix "const" do anything differently at a hardware level or is it just protection for the coder? [duplicate]

This question already has answers here:
Does "const" just mean read-only or something more?
(7 answers)
Closed 8 years ago.
Does
int x = 5;
and
const int cx = 5;
do anything differently at the hardware level? I've never understood that.
In other words, if I declared int x = 5; and then never tried to use x as an l-value anywhere else in my code, would it compile the exact same as if I had declared x constant? Is it just a protection against careless programming?
It's just protection from the programmer. If you do the right messing around with const_cast, you can override const-ness and write to const variables. Assembly code can modify const variables just like anything else. However, if you change the value of a const, the new value may not be visible in all contexts, because compilers aggressively in-line constants.
In certain circumstances it can cause the compiler to use your promise of constness to enable further optimizations.
The best example for this is with static integral values. If they are const as well, the compiler will treat them more like aliases for the value than like variables. In fact, you can utilize this to create values that do not have any addresses at all. An example of this can be found here.
Additionally, const-ness is sometimes used to represent hardware facts in your program: To represent the fact that string literals are oftentimes stored in read only memory, the characters they contain are const.
It is protection against careless programming.
An optimizer may also use it as a hint that certain types of optimizations can be performed, I suppose.
It also tells the compiler that certain things are const which allows you to do stuff like pass temporary instances through reference parameters or as default parameters:
void function (const Object &o) {
}
void another (const Object &o = Object(1234)) {
}
function(Object(5678));
another();

Why using const for arguments passed by value? [duplicate]

This question already has answers here:
Const correctness for value parameters
(6 answers)
Closed 9 years ago.
Say you have:
int f( const T a ) { ... }
int g( const T &a ) { ... }
I understand the use of const in g: we don't know how a is used outside the function, so we want to protect it from being modified. However I don't understand the use of const in f, where a is a local copy. Why do we need to protect it from being modified?
I can think of a few reasons:
1) When someone reads the code and see const T a, they know that a should not be modified in the body of the function.
2) The compiler will tell you when you try to modify a in the body of the function. Therefore, adding const can prevent mistakes.
BTW chris already mentioned this in the comments.
3) However, there is another difference in C++11. A constant object cannot be moved from, as a move operation modifies the object. Therefore, you can only make a copy of a in the function body and cannot move from it.
4) Also, if this is a class type, you cannot call non-const members functions on a const object.
Declaring variables const is a good practice.
WHY?
For arguments passed by value to functions, it doesn't matter for the caller whether you declare it const or not. The rationale here is to protect yourself from mistakes while coding, using the compiler to warn you that you are changing the value of a variable, so that you can explicitly confirm this behavior by removing the const modifier. This applies not only to function parameters, but also to local variables.
Based on this rationale, I personaly always start out by declaring all variables const and let the compiler to issue errors when I modify them. Then I check if this behavior is intended and remove the const modifier if it is indeed needed. For better legibility I also always prefer to code in a way my variables are all const.
"I personally tend to not use const except for reference and pointer parameters. For copied objects it doesn't really matter"
If you are using const in function argument there may be one of the following reason.
1-it help the compiler to optimize things a bit.
2-no body can modified argument value in future(if many people working on same code base)

Why const after void/int declaration? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
is const (c++) optional?
Constant Member Functions
I have seen different posts around about int a() const. My question is exactly why do we want to put the const keyword there? I know that it prevents us from making changes on members of the class the function is in, but so what?
We could just write a comment above the function and tell the coder not to make any changes to the class itself inside the function, but why do we really care about the const after the void declaration? In which scenarios may there be a better way to use for example int a() const instead of just int a() and does the compiled code change at all?
It does make a difference. Consider A to be a class with a print() method. Then this:
const A a;
a.print();
only compiles is print is defined as const.
Of course, the main reason is to prevent any changes to the object inside the class. The
We could just write a comment above the function and tell the coder not to make any changes to the class itself inside the function
is just wishful thinking. This doesn't really happen. So if someone doesn't read the comment (or does and ignores it), you'll get compiler errors.
There's also the benefit of optmization - the compiler can better parallelize tasks on const objects because it can assume they don't change between operations on them.
There are three basic reasons to use const functions:
1) C++ only allows const references can be bound to temporaries. But if you don't have useful const functions, const references are useless.
2) Some libraries, such as the C++ standard library, provide specific semantic guarantees that only apply to const functions. For example, you are guaranteed on standard collections that you can access const functions of the collection from multiple threads concurrently.
3) It allows easy-to-make mistakes to be caught by the compiler. For example, if you intend to rely on the C++ standard container guarantee, if you use a const object, you only can call const functions. So a mistake, say someone modifying the code forgetting about the concurrency issues, will get caught at compile time. (Rather than when someone is relying on your program to do real work.)
The benefit of declaring a member function const is, that the compiler will emit an error, if you modify the object. So, even if you modify the object accidentally, the compiler will catch your mistake.

const best practice in function declaration

Ive searched through the archived posts but I couldnt find anything similar.
Just a simple question: whats the best practice in declaring inspecting functions like:
int foo(int a) const { return a+1; }
Im referring to the const keyword, do you usually declare it at the end of an inspecting function? Im just asking because I usually do, even if 99% I wont declare any const class.. I just keep on tellin myself that it could save me some time if I ever should need to, but I was wondering if anybody else really cares about declaring const functions or if Im just paranoid about typesafe code
Assuming that you are talking about member functions (non member functions cannot be const ever), you should write const-correct code always, and that means that each and every function that does not modify the visible state of the object should be const.
Even if you don't ever create a constant object of the type, in many cases you will pass the object to a function through const references and in that case, only const member functions can be called on the object (Incidentally this means that you should pass the object by constant reference to any function that does not need to change the state of the received object)
The const appended at the end of the function declaration and definition indicates a contract between the caller of the function and the function that the function will not modify any members of that class.
So if your function provides guarantee for such an const-correctness contract you should extend it to users of your function.
Yes, of course you should if you want your program to support const correctness.
Const correctness has a way of propagating through your program once you begin declaring instances as const. As program complexity and your use of const increases, then you will either:
encounter many compiler errors when using const objects if you do not add them now
or your program will build without (or fewer) errors once you favor using const in the appropriate places.
or you may end up avoiding const for some time - which is (IMO) not a good road to go down if you want to improve your designs.
Over time, many of us have learned to use const in more than 1% of our code.

How often do you declare your functions to be const?

Do you find it helpful?
Every time You know that method won't change state of the object you should declare it to be constant.
It helps reading your code. And it helps when you try to change state of the object - compiler will stop you.
As often as possible. Functions that don't need to change data members should be declared as const. This makes code more understandable and may give hint to the compiler for optimization.
When you have a const object, the only methods that the compiler will let you call are those marked safe by the const keyword. In fact, only member methods make sense as const methods.
In C++, every method of an object receives an implicit this pointer to the object; A const method will simply receive a const this pointer.
Assuming you're talking about methods, as in:
struct Example {
void f() const;
};
Then if they should be callable on a const object, the method should be const.
Not often enough....
While all the answers are correct, if you are using a libary that is not const correct then it is difficult to use const all the places you should use it.
If you have an old API that takes a char * that for all logical purposes should be a const char *, then you either have to forget const in your code or do some ugly casting. In that case I forget const.
I use const at almost every opportunity, and like the fact it provides both documentation of intent and enforces compliance with that intent. Language features don't get much better than that, and yet const is curiously unloved. (The reality seems to be that the majority of self-proclaimed C++ coders can't explain the difference between int*, int*const, const int* and const int*const.)
While it could never have happened due to its 'C' origins, I often think C++ would be a better language if const had been the default and a liberal sprinkling of (say) 'var' or some similar keyword was necessary to allow post-construction modification of variables.
I used to declare functions as const but now I rarely if ever do it anymore.
The main problem was that if I wanted to change a function from const to non-const, it would mean that all other const functions calling that function would also need to be changed to non-const.
That happened more often than I thought due to optimization. For example I had a GetData() function which used to return a pointer to the data, but I later optimized to only set up the data if GetData() ends up being called (which changes the object's state, so it's no longer a const function).
Same thing for other functions that could do some calculation without changing the object's state, but at some point it made more sense caching the result since the function was called many times and was a bottleneck.
Also in practice, at least for my project, I saw very little benefit from declaring my functions as const.