0

I'm looking for a way to create a "variable-function" in C language. In MATLAB i'm able to create something like:

my_function = (@x) sin(x) + x^2 + x;

so that i'm able to evaluate it for any value of 'x' i like:

my_point = 3.09; my_function(my_point);

is there anything like that for C language?

2 Answers2

1

That's just a regular C function. The terminology would be: "A function with arguments"

double my_function(double x)
{
  return sin(x) + x*x + x;
}
Philip
  • 1,539
  • 14
  • 23
-1
#include <stdio.h>
#include<math.h>
#define my_function(x) sin(x) + pow(x,2) + x
int main()
{
    double my_point = 3.09;
    printf("%lf",my_function(my_point));
    return(0);
}
Nur Hossen
  • 31
  • 8
  • But if you now do `my_function(my_point+1)` you get the wrong answer! – Cris Luengo Dec 13 '18 at 21:37
  • use #define my_function(x) sin(x) + pow(x,2) + x then you get the right answer. – Nur Hossen Dec 13 '18 at 22:07
  • 1
    The correct way to define macros in C is to add lots of parenthesis everywhere. Your updated macro still doesn't do the right thing for `my_function(x>>2)`, for example (bitshift `>>` has lower precendence than `+`). And you need to add some around the full expression as well, as `2 * my_function(my_point)` doesn't produce the right answer either. Correct is something like `#define my_function(x) (sin(x) + (x)*(x) + (x))`. You can't have too many parenthesis in a macro, there's always unexpected inputs... – Cris Luengo Dec 13 '18 at 22:22
  • Why would a preprocessor macro be appropriate here instead of just a regular function that takes a parameter? – Jesper Dec 13 '18 at 23:25