john smith
john smith

Reputation: 649

Nested function alternatives in C++

I want to make a function f() that uses three values to compute its result: a, b, and e. e is dependent on a and b, so technically f() is only a function of a and b. But for the sake of readability, it is easier to look at a function containing the abstraction e than to look at a messier formula containing many a's and b's.

Is there any way to use dependent variables like e without the use of nested functions, which C++ does not allow?

Upvotes: 2

Views: 473

Answers (6)

Starvae
Starvae

Reputation: 1

I think that you can write some notes.

int FuncSum(int a, int b)
{
    //return the sum of a + b
    return a + b ;
}

Upvotes: -1

Ergwun
Ergwun

Reputation: 12978

Not sure I understand your question, but if you're just after a way to make your function more readable by introducing a dependent variable, why not just calculate that variable in a separate function called by your main function:

float CalculateE(float a, float b)
{
    return (a + b);
}

float f(float a, float b)
{
    float e = CalculateE(a, b);
    return a + b + e;
}

Upvotes: 2

Keith
Keith

Reputation: 6834

You can do this:

int f(int a, int b)
{
    struct LocalFunc
    {
        int operator()(int a, int b)
        {
            return a*b + b*b*b;
        }
    };
    LocalFunc e;
    return e(a,b)*a+b;
}

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361582

You can write a local struct which can define a static function, which can be used as if its nested function as:

int f(int a, int b)
{
   struct local
   {
        static int f(int a, int b, int e)
        {
             return e * (a + b);
        }
   };
   return local::f(a,b, a*b);
}

Upvotes: 2

Mark B
Mark B

Reputation: 96281

What's wrong with:

int compute_e(int a, int b)
{
    return whatever;
}

int func(int a, int b)
{
    int e = compute_e(a, b);
}

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283713

C++ does have local variables, which makes this easy:

double f(double const a, double const b)
{
    double const e = a * b + b * b * b;
    return a + b + e;
}

Upvotes: 4

Related Questions