samedi 6 janvier 2018

C++ variables loosing values when passed to function

I am creating program to calculate math expression ax^2 + b*x + c, a,b,c are passed to quadraticExp() and x is passed from quadraticExp(a,b,c)(x).

#include<iostream>
#include<functional>
#include<cmath>

auto quadraticExp(double a, double b, double c) -> std::function<double(double)>
{
    //return auto f1 [&] (double x) -> double   
    return [&] (double x)
    {
        std::cout<<a<<" "<<b<<" "<<c<<" "<<x<<std::endl;
        return ( a*std::pow(x,2) + b*x + c );
    };
}

int main()
{
double a={1.0}, b={1.0}, c={1.0}, x={3.0}   ;
std::cout<<quadraticExp(a,b,c)(x)<<std::endl;
return 0;
}

Output is:

1 8.00798e-307 1.83847e-307 3
9

  • So variables b,c are loosing their values. Why is this happening and how can I get rid of that?
  • Can I write full definition of lambda object //return auto f1 [&] (double x) -> double so I can reuse f1 in the function?

Aucun commentaire:

Enregistrer un commentaire