Solved

C++ const keyword

Posted on 2014-01-14
5
308 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Suggested Solutions

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
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.

832 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