Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] Pass result "y" to inline function



  • Hi!

    I have to pass the result "y", which is correctly calculated in a function in mainwindow.cpp, to the inline function in the header file (where "y" is needed):

    inline double f(double x)
    {
          double y;
          return y+3*x;
    }
    

    this function is called in the same function of the mainwindow.cpp-file where "y" is calculated before.

    It compiles fine, but "y" is not passed.

    How can I tell the programme to pass "y" to be used in the inline function of the header?

    I appreciate any useful comments!


  • Lifetime Qt Champion

    Hi,

    That's rather a general C++ question but:

    Is y a member of your class ? If not, add it as parameter to f otherwise, remove double y;

    On a side note, you should consider using more meaning full names for your functions and variables. Your code will be way easier to read and understand.



  • Thanks @SGaist ! Solved!

    I changed it to:

    inline double fun(double x, double constant)
    {
    return constant+3*x;
    }

    and it works!



  • I can't get the point, but I'll try: You want the y to be passed to the fun with its calculated before value? Am I right? If so, you probably want to pass it by reference:

    inline double fun(double x, double& constant) {
        return constant+3*x;
    }
    

    Also, you should not call variables "constant" until they're constant like const double sum; or whatever with const keyword.


  • Lifetime Qt Champion

    @sosun, why as a reference ? constant is just used not modified.

    But I agree on the naming point. By the way, a constant that is recalculated is not really a constant



  • @SGaist Aah, I didn't understand the question rightly. You was right.



  • @SGaist that's true!

    "x" is the variable or better "argument" of the function "fun". The constant is basically the result of a variable from a function from within an interval. Nevertheless, it is calculated before "fun" is called and it is simply not changed any more within the function! So I renamed it to "resultbefore" :-).

    inline double fun(double x, double resultbefore)
    {
    return resultbefore+3*x;
    }
    

    Anyway, it works! There was a another small problem which I have removed now. Also thanks to @sosun !


  • Lifetime Qt Champion

    Again, it's not really better. What does that variable represent ? Number of atoms in a quartz crystal ? Number of waves hitting a riff ? That's the kind of thing you should refer to when deciding variable names.


Log in to reply