0

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;
}
1
  • 1
    I don't see a call to sort. Commented Feb 21, 2014 at 14:26

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Why should i need to add sort(); line in main, i have created a function pointer and am passing the address of the function to it, it should automatically switch to that function right. Can you please explain
@user3336874: Telling the machine that an address of some function is tobe stored somewhere (as done by assigning something to sort) does not yet tell the machine to execute the code at that address.
@user3336874 assigning is fine, but as long as you are not calling the function using sort(), how it will be executed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.