Jump to content
  • Advertisement
Sign in to follow this  

Question about constants

This topic is 4004 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What does it mean: const int function() { // something.. } i understand that it means that you cannot change the return value, but how can i change the return value..?

Share this post

Link to post
Share on other sites
In this particular situation, it is completely useless, since the returned value would be a temporary value (and thus, wouldn't be modifiable) anyway.

However, you may wish to return a value by reference (perhaps to avoid creating a copy of the value, or perhaps because you want changes applied to that value to be received by the holder of the return value) but do not wish to let the one who called the function modify the referenced value.

A typical example is v.front() when v is a const std::vector<int> (at which point, the function returns a const int &).

void foo(const std::vector<int> & v)
// Function foo may not alter the vector which
// it receives, and this includes altering the
// value of its first element!
const int & i = v.front();
std::cout << i << "\n";

// However, it's possible to alter the vector
// through a variable other than 'v', perhaps
// if the original vector is a global variable
// that was passed as an argument:
g_v[0] = 100;

// And now, this outputs 100.
std::cout << i << "\n";

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!