0

I need to know can i do something like this in C. I have 3 functions like this one:

int fun1 ()
{if (condition) 
{return 1;}
else
{return 0;}}

and then I have an array of function pointers, and I want to compare it with a number 1 (compere results of functions!!).

int (*fun_ptr[3])() = {fun1, fun2, fun3}; //all 3 functions in array
int i;
if ((*fun_ptr[i]) = 1)
 { //do something}
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Marta
  • 1
  • 2
  • `i` is undefined when it is used. And how do you expect to "compere results of functions" without calling any functions? – Scott Hunter Feb 17 '21 at 19:12
  • Can you explain your purpose more clearly? – Ogün Birinci Feb 17 '21 at 19:14
  • Yes, you can do pointer compares to integers, but very often this is not what you actually want to do. In your example, I really really doubt the address of any of the functions is `1`. If instead you wanted to run each function in the array and see if the result was 1, that is much more common. – Michael Dorgan Feb 17 '21 at 19:14
  • https://stackoverflow.com/questions/252748/how-can-i-use-an-array-of-function-pointers – Michael Dorgan Feb 17 '21 at 19:16
  • `if ((*fun_ptr[i])() = 1)` ===>>> `if ((*fun_ptr[i])() == 1)` – 0___________ Feb 17 '21 at 19:19

1 Answers1

0

Assuming you want to call through an array of functions looking for one of those functions to return 1:

Notice that all function signatures must be identical for this technique to work - in this case they all return int and accept void.

For more examples: How can I use an array of function pointers?

int fun1 ()
{
  // Place the condition you want to check here - might make more sense to pass it in as a parameter to all functions...
  if (/*condition*/ 1) 
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

// Assuming this functions would do something more useful in your case - PH so it compiles.
int fun2 () {return 0;}
int fun3 () {return 0;}

int main(void)
{
  int (*func_ptr[3])() = {fun1, fun2, fun3}; //all 3 functions in array

  // Loop through all functions - note we should use a sizeof() trick on the func_ptr array to be more correct on array size.  
  for(int i=0; i<3; i++)
  {
    // Call each function and check for "1"
    if((*func_ptr[i])() == 1)
    {
        
      // If "1", do something
    }
  }

  return 0;
}

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61