Question

I have used function pointer in this, but not able to understand why it is not working, here is my piece of code. when i run this code i get not output, i was expecting Decending order and Ascending order to be printed when i give -r in command line, and if no command line input is given it should print ascending order.

What has gone wrong in my code ??

#include <stdio.h>
#include <stdlib.h>

void decending_sort()   {
   printf ("Decending order \n");
}

void ascending_sort()   {
  printf ("Ascending order \n");
}

int main( int argc, char **argv)  {

int i;
void (*sort)();

while (*++argv) {
    if ((strcmp ( *argv, "-r" )) == 0)
        sort = decending_sort;
}
sort = ascending_sort;
}
Was it helpful?

Solution

You define sort as function variable, assign a value to it, but never call it, so neither decending_sort() nor ascending_sort() is ever executed.

To invoke it add this last line to `main()

  [...]

  sort();
}

Also: Functions without any parameters shall be declared like this:

void decending_sort(void);

Either should be a variable of their type

void (*sort)(void);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top