How to call a function in time of execution in c [closed]

1

For example with this pseudocode

   function suma(a,b)
    {
    return a+b
    }

    function callfun(namefunction,arg1,arg2)
    {
    namefunction(arg1,arg2)
    }

I also need to know how to make a console and     from the console I write this to call the sum function

callfun(suma,3,3)
    
asked by jony alton 08.12.2016 в 18:45
source

2 answers

3

Short answer: No but Yes.

Long answer:

What you propose is typical of interpreted languages, which can Locate functions by name at runtime.

C is compiled , and it does not allow factory to do what you indicate. However, an approximation is possible, but with function pointers

void function1( int a ) {
  ...
}

void call( void ( *f )( int ), int v ) {
  *f( v );
}

void ( *ptr )( int ) = function1;
call( ptr, 10 );

To select one of several functions, you can use a structure and an arrangement:

struct ident {
  char *name;
  void ( *ptr )( void );
};
struct ident functions[];

And you go through the arrangement looking for the indicated name.

And, if you want more flexibility, you use functions with variable arguments:

#include <stdarg.h>

void funct( const char *fmt, ... ) {
  va_list ap;

  va_start( ap, fmt );
  ...
  va_end( ap );
}

and declare the pointer as

void ( *pointer )( const char *, ... );

I think that with the above and you can go pulling some code to show us ...

    
answered by 08.12.2016 в 19:20
2

Functions are always called at runtime, that's when the program opens.

For the sum is easy, instead of function , it should be float , and the parameters a and b should be float too, since it is a sum of real numbers.

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

The callfun function, as it does not have the return statement, returns a void , but the parameters, we do not know what type they are, so I name them, Tipo_1_1 , Tipo_1_2 , Tipo_1_3 , Tipo_2 and Tipo_3 , but it could be any type of data, void , int , char .

void callfun(Tipo_1_1 (*namefunction)(Tipo_1_2,Tipo_1_3),Tipo_2 arg1,Tipo_3 arg2)
{
    (*namefunction)(arg1,arg2);
}

To call it would be the following, just add a semicolon ; .

callfun(suma,3,3);
    
answered by 08.12.2016 в 19:30