Weldon40
Weldon40

Reputation: 31

How to check if a function parameter is constant?

This may be easy and I could be just missing what is right in front of me. However, I cannot figure out how to ensure a function parameter, passed by reference, can be modified. Essentially i need the following:

bool calculate(double lat, double lon, double dep, 
               double &x, double &y, double &z)
{
    if (x, y, AND z are NOT const)
    {
        perform the proper calculations
        assign x, y, and z their new values
        return true;
    }
    else //x, y, or z are const
    {
        return false;
    }
}

The "if" statment check is really all i need

Again I apologize if this is already on this site or if it's a standard library function that i'm missing right in front of me. I come here all the time and virtually always get a good answer but I could not find anything on this already on here.

Upvotes: 2

Views: 430

Answers (1)

rabensky
rabensky

Reputation: 2934

if you have double &x then it isn't a constant. If you have const double &x then it is a constant.

In your case - no need to check, they aren't constants. The check is automatically performed in compile time.

See this:

void func(double &x){  X=3.14;  }

double d;
const double c_d;
func(d); // this is OK
func(1.54); // this will give an ERROR in compilation
func(c_d);  // this will also give an ERROR in compilation

You simply can't call a function that wants a (non const) reference with a constant.

This means that the compiler finds some bugs for you - like in your case, you don't have to return true or false, and you don't need to check it to try and find bugs - you simply compile and the compiler will find these bugs for you.

Upvotes: 8

Related Questions