Solved

C++ const keyword

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now