Why const after void/int declaration? [duplicate] - c++

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.

Related

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)

Const correctness of function parameters, that are passed by value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Const correctness for value parameters
I consider a good coding practice the following. When a parameter is passed to a function by value, it should only be read, but not modified (or reused) in the function body. But is it actually a good practice?
Example (of what I avoid doing):
int foo(int x){
//do lots of cool stuff
x = 69;
//do even cooler stuff
}
From here on we get to const correctness. Provided that my practice is good follows that nearly every argument to every function should be preceded by a "const". Actually "a" is optimistic:
class A{
const int gnoo(const int *const, const double) const;
};
There are two sides to the problem, the declaration and the definition. At the declaration point, the top level qualifiers of the function arguments are dropped, so the const is removed by the compiler. At the definition on the other hand, the compiler ensures that if the parameter is const it will not be modified internally.
The return type is another story, where the const is not dropped from the declaration, but in this case you most probably don't want to make the returned object (if it is by value) const, as that will possibly limit the chances of optimizing of your compiler in a couple of different ways. The first one, brand new in C++11 is that you cannot move out of a const object, which means that by returning a const object you inhibit moving from it. In C++03 the cases where this affect are fewer and more of a corner case, but there is limited advantage on returning const objects.
Some people suggests adding const everywhere. I don't, and most code I have read does not either.
Your point is well taken. And depending on the language, the compiler/interpreter may throw an error or warning when it sees code like your first example.
However, at some point you have to choose whether or not you are going to try and protect "the developers" from doing something stupid or just assume that they are and catch this sort of thing during a code review.
Utilizing syntactic mechanisms to make the code safer is a good thing, IMHO. It can sort of impede development flow, unfortunately.

Const correctness warnings c++

Does anyone know of any warnings that C++ compilers provide that help to enforce const correctness? For instance, it would be nice to have a warning produced by any C++ method that contains a non-const parameter that is never modified inside of the method. I see that there is a gnu compiler warning called -Wsuggest-attribute=const; however, when I use this flag I get an error saying that it is not recognized. Any ideas why?
I don't think such a warning exists, mostly because it would be useless. Just because a parameter is not modified inside the call, doesn't mean it should be made const just for the sake of it.
Think of virtual functions. Perhaps the designer of the base class, although not modifying the parameter in the base class, wants to leave it up to an extending class whether or not to modify that parameter.
Also, think of large applications, where modifying interfaces or API's or whatever costs a lot. You might not need to modify the parameter now, but intend to do so in the future. You're not going to make it const now, and force a full rebuild and probably risk errors in the future when you remove the const.
-Wsuggest-attribute=const
This analysis requires option
-fipa-pure-const
which is enabled by default at
-O
and higher
Careful, a const parameter like this one:
void myFunc(int const param);
does not belong to the interface. It belongs to the local scope of the function implementation. In fact, this function:
int inc(int const param) { return param+1; }
may be declared as
int inc(int param);
It is not a violation of the const correctness paradigm to claim the right to modify a variable but not actually do it.
If you are worried about const_cast you can either not use it in the first place or simply grep for it in your code base.
No, unfortunately there are no such warnings. You just get errors if you try to change const declared parameters. This is because missing const declarations do not change the correctness of the code from the compilers point of view. But const correctness is important for the compiler to discover potential optimizations and it improves the readability of the code. It is a matter of professionalism. Especially when using references const correctness is a must. I often refer to this.
The compiler itself takes const correctness very serious when operators (assignement, conversion, ...) come into play. A missing const here and the compiler refuses to use the operator because it makes a big difference if the given parameter may possibly be modified or not.
I'm not aware of such warnings and I think they would be rather hard to implement in a compiler - that is, they would slow it down. Maybe some static analysis tools have such features (but I'm not aware of those either).
As per Wsuggest-attribute=const, that is a different thing. It will suggest to use a gcc-specific "function attribute const", which is, basically, a mathematical function, receiving only values (no pointers), not reading or changing any static/global state and returning only a value (no pointers). For further description, look here: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

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.