I recently came accross this code:

Mat3D R_z(double RotAngle)
{
  const double S = sin (RotAngle);
  const double C = cos (RotAngle);

  Mat3D U;

  U.m_Mat[0][0] =  +C;  U.m_Mat[0][1] =  +S;  U.m_Mat[0][2] = 0.0;
  U.m_Mat[1][0] =  -S;  U.m_Mat[1][1] =  +C;  U.m_Mat[1][2] = 0.0;
  U.m_Mat[2][0] = 0.0;  U.m_Mat[2][1] = 0.0;  U.m_Mat[2][2] = 1.0;

  return U;
}

My question: why should the keyword const be used in this case?
The variables C and S are IMHO just a bit of syntactic sugar, to make the rest of the code somewhat easier to read.

Recommended Answers

All 15 Replies

Some people use const with every variable that is not meant to change, for the simple reason that it might reduce chance of bugs is complicated code due to dev error.

commented: Yes. Experts. +14

i agree with Suzie999. the 'const' key word is for avoid that the variable value is changed. good for function parameters(1 time i was getting problems, until i change the parameter(on header function) to const.
maybe, when you change the positive\negative values, you realy need the const.
but for test try these:

Mat3D R_z(double RotAngle)
{
   double S = sin (RotAngle);
   double C = cos (RotAngle);

  Mat3D U;

  U.m_Mat[0][0] =  +(C);  U.m_Mat[0][1] =  +(S);  U.m_Mat[0][2] = 0.0;
  U.m_Mat[1][0] =  -(S);  U.m_Mat[1][1] =  +(C);  U.m_Mat[1][2] = 0.0;
  U.m_Mat[2][0] = 0.0;  U.m_Mat[2][1] = 0.0;  U.m_Mat[2][2] = 1.0;

  return U;
}

is just a thot: maybe the Suzie999 can correct us the diference(i didn't tested the code)
like you see they aren't const and their values are inside of parentheses('()'). maybe in these way, their values aren't changed and only show them with the negative\positive signal

it might reduce chance of bugs is complicated code due to dev error.

Could you elaborate on that?
I'm not really convinced by your answer.
I really don't see why one should use const in a simple function here

ddanbe: i belive that i don't have your experience, but we must, for exemple, use the const on class constructors and overloading operations for not lose data. and some errors are dificulty to find them, because the compiler don't detect them.
on these simple function we don't need use the const... so why he used? maybe because the negative\positive can change the variables results, i don't know... and maybe the '()' can avoid that problem. but for he use the 'const' it's because his variables are changed on some place

15. Use const proactively.

Summary

const is your friend. Immutable values are easier to understand, track, and reason about, so prefer constants over variables wherever it is sensible and make const your default choice when you define a value. It's safe, it's checked at compile time,
and it's integrated with C++'s type system.  ...


Discussion

Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:

void Fun( vector<int>& v)
{  //...
   const size_t len = v.size();
   //... 30 more lines ...
}

When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do). It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true.

...

From: 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices' by Sutter and Alexandrescu

It's not I dislike const I'm a great fan. I use const whenever I can.
But why use it in only a few lines of code?
Just plain good habbits?
The compiler turns it into optimal code, if written with const?

I believe so, once you get into a mindset of using const keyword like that it just becomes natural no matter how non or complex the method is.

It's a really good mindset I think, especially if you're coding in C or C++ with all those pointers knocking around.

I will have to agree with @Suzie999 on this. Once you get into the mindset of using const whenever you have a constant value then you should just keep on using it. Not only does it keep the that behavior front an center but it is someting you should always because it makes the type system work for you.

There is also another posible side effect of doing this. If the compiler can determine what the value is at compile time the compiler coudld subsitute the value of the calclation into an actual constant in the code. This would save you the runtime of the computation during runtime as well as the function call.

Thanks you all for your answers. I guess this solved it.

Another thing const does is allow the compiler to perform some extra optimizations, which means that the program can potentially run faster and use less memory. But yeah, as the others have said, using const everywhere makes you think when the compiler complains, "Do I really need to change this value?"

Lots of good answers here! In this particular example, const is not required, but may, as indicated by others, allow the compiler to utilize some optimizations which may (or may not) help performance.

once you get into a mindset of using const keyword like that it just becomes natural no matter how non or complex the method is.

Yes. Yes.

In this example, the notion that the const-qualification may somehow 'allow the compiler to perform some extra optimisations' was true in some prehistoric era. If the entire context of use of an object is visible to the compiler (ie. the const-qualified object is not aliased, is not at namespace scope with external linkage, is not a parameter of a non-inline, non-template function with external linkage, etc.), it knows everything about what is going on with that object. It is a lot better at static-flow analysis than most programmers; and the "as-if" rule allows it to rewrite the code.
http://en.cppreference.com/w/cpp/language/as_if

C++11 deprecated the use of the keyword register - compilers know what would be optimally placed in a register better than programmers; for about twenty years or so, they have been just ignoring the register keyword as an optimisation hint. Just as they have been ignoring inline as an optimisation hint.

const in a purely local context is for the programmer; it makes no difference to the optimiser.

As an example, with optimisations enabled, this code

namespace
{
    unsigned int at_namespace_scope_with_internal_linkage = 0 ;
}

int foobar()
{
    at_namespace_scope_with_internal_linkage -= 100 ;

    /* const omitted */ auto a = 52 ;
    auto b = a / 2 ;
    auto c = a + 5 ;

    if( b < a )
    {
        b += a ;
        c -= a ;
    }

    b *= a ;

    if( b < c )
    {
        b += a ;
        --c ;
    }

    else
    {
        b -= a ;
        ++c ;
    }

    at_namespace_scope_with_internal_linkage += a ;
    ++b ;
    --c ;

    at_namespace_scope_with_internal_linkage += a - 4 ;

    return a + b + c ;
}

is rewritten by a modern compiler "as-if" it were:

namespace
{
    unsigned int at_namespace_scope_with_internal_linkage = 0 ;
}

int foobar() { return 4062 ; }

Snippet with annotations:
http://coliru.stacked-crooked.com/a/123880d0cc1a3005

@vijayan121 I just wanted to let you know about this other online compiler with assembly view: http://goo.gl/64kMZO

commented: awesome online compiler! +15

NathanOliver, thank you very much!

In additions to an assembly view, it has ICC and several versions of the GNU and LLVM implementations.

hmp if something is const then it is faster like that, don't forget there is const cast in moder C++

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.