Solved

C++ const keyword

Posted on 2014-01-14
5
300 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
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.

763 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

11 Experts available now in Live!

Get 1:1 Help Now