Solved

C++ const keyword

Posted on 2014-01-14
5
323 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
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.

635 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