Solved

C++ const keyword

Posted on 2014-01-14
5
313 Views
Last Modified: 2014-01-16
What's the difference between:
MyFunction(int i);
MyFunction(const int i);

Open in new window

When would I want to throw in the const keyword? Can I also throw it in the return value? e.g.
int MyFunction();
const int MyFunction();

Open in new window

0
Comment
Question by:deleyd
5 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 60 total points
ID: 39781152
Yes, both is possible. The key difference is that both the argument and the return value are considered to be unchangeable by the compiler. IOW, 'i' will be a constant value when be passed in a call and (if applied) the return value will be treated as a const value. See also http://en.wikipedia.org/wiki/Const-correctness
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 60 total points
ID: 39781158
BTW:

>> When would I want to throw in the const keyword?

Always when you are sure that the value isn't to be changed. The Wikipedia article will provide some more explanatory examples ;o)
0
 
LVL 1

Assisted Solution

by:philrosenberg
philrosenberg earned 20 total points
ID: 39781935
It is more relevant when passing references or pointers. For example if I have std::vector<double>, which is basically a C++ array of doubles if you are not used to using the std template library. It could have many elements and I don't want to copy them all when I pass it to a function, so I pass it by reference

int myFunc( std::vector<double> &myVector );

However this gives two related side affects, first if someone else wrote myFunc, I wouldn't know that my vector would be guaranteed to be unchanged, so if I needed it to stay unchanged it would make me think I needed to copy it myself then pass the copy. The second is that if I have a const std::vector<double> I cannot pass it in. For example

const std::vector<double> unityVector(5, 1.0); //create a const vector of 5 elements each with a value of 1.0, that cannot be changed
int result=myFunc(unityVector); //won't compile

To fix this, we instead use

int myFunc( const std::vector<double> &myVector );

In your case you are passing by value, so it actually makes very little difference, basically by making i const you are ensuring that you don't accidentally change i within your function. You may consider this a good thing, but I think some people find it a bit misleading as they expect consts to be references.

When it comes to the return type, if you return a const then it cannot be modified until after it has been assigned so if you had

const int myFunc( int i );
int increment( int &i )
{
    i=i+1;
    return i;
}

The following wouldn't compile
int myInt=++myFunc(5); //cannot increment the const return
iny myOtherInt=increment(myFunc(5)); //still doesn't work as I can't pass the const returned value into the increment function

but the following would be fine
int myInt=myFunc(5);
++myInt;

Note also that the following fails
increment(5); //5 is a const so cannot be passed into the function which takes a non const
0
 
LVL 16

Assisted Solution

by:HooKooDooKu
HooKooDooKu earned 20 total points
ID: 39782307
As I see it, the 'const' key word has two purposes:
1. It's a way to check yourself to make sure you don't try to accidentally change a value you didn't intent to.
2. It gives the compiler a hint on how to optimize code.  

Simple Example:
for( int i = 0; i < x; i++ )
{ do stuff }

If 'x' above is declared as const, the compiler can utilize that information to optimize this loop by doing things like loading 'x' into a register, and simply referencing that register each time it needs to decide if the for...loop should continue.

But if 'x' is NOT declared as const, the compiler must fetch the value of 'x' each time it needs to decide if the for...lop should continue because something inside the for...loop could be changing the value of 'x'.
0
 

Author Closing Comment

by:deleyd
ID: 39785937
Thank you for the explanations. (I apologize I should have made the question worth more points as the answer was a bit complicated.)
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question