Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using "const" with scalar type? (e.g. "const double" or "const int")

Tags:

c++

///////////////////////////////////////
class A {
    ...
    const double funA(void)
    {...}
};

A a;
double x = a.funA(); 
// although the intention is to
// enforce the return value to be const and cannot be
// modified, it has little effect in the real world.

class A2 {
    ...
    double funB(void)
    {...}
};

///////////////////////////////////////
class A {
    void setA(const double d)
    { // now you cannot change the value of d, so what?
      // From my point of view, it is NOT a good practice to change the pass-in parameter
      // in this case, unless you want the caller to receive that change
      // instead, you can do 
      // const double dPassIn = d;
      / /then use dPassIn instead.
      ...
    }
};

class A2 {
    void setB(double d)
    {...}
};

//////////////////////////////////////

From my understanding, we should prefer to using A2::funB and A2::setB because the const used in both A::funA and A::setA has little meaning.

// Update //

    FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index, 
                                FMOD_REVERB_PROPERTIES *props, char **name = 0);

I consider FMOD is a well-designed package and it does use const int inside function parameter list. Now, I agree that the A::setA(const double d) has its edge.

like image 848
q0987 Avatar asked Dec 06 '11 21:12

q0987


2 Answers

When returning by value the constant has no effect as it cannot be enforced anyway. Some compilers issue a warning. However it DOES make sense to return a pointer/reference to constant data.

When passing an argument into a function it is preferable (safer, allows for compiler optimizations) to pass it as a constant unless you absolutely need to change the data.

like image 132
Petr Avatar answered Nov 05 '22 06:11

Petr


the const-keyword tells the Compiler "In my function setB i Wont change the Argument. If you want to Optimize for Multithreading you can use this Variable the same Time in another context, because my Work wont change it."

So i would say, in Progamming-logic, the second variant is better, like you said it has "little meaning", but in wider logic if you see what really happens, you should declare const, what is const, and dont declare const what isnt const. It is kind of a documentation the compiler understands and maybe will use to optimize your code!

like image 39
EGOrecords Avatar answered Nov 05 '22 06:11

EGOrecords