Search code examples
c++variablesconstants

Is it considered good practice to use const for local variables?


These last weeks, I found myself using a lot of const everywhere. Not only in methods or arguments declarations, but even for temporary variables.

Let me illustrate with a simple function.

I used to write:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  unsigned int result1 = p1.computeResult();
  unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

But now it is more like:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  const unsigned int result1 = p1.computeResult();
  const unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

The latter makes more sense to me and seems less error prone. (I admit that in this example, it doesn't really matter) However I've seen very few code samples where const was used on temporary/local variables. And I'd like to understand why.

Is there any reason why this isn't a common case ? Am I abusing with my use of const ? Or is it just me that has been looking at the wrong samples ?


Solution

  • Using const on local variables improves code clarity, so it's a good idea. You see const and you immediately know that the variable is never changed later in scope. It's from the same series as making functions short and returning early.

    Developers are lazy - they often think that it's a useless word that doesn't change anything. IMO they are wrong.