Difference between revisions of "OOP344-Jason Quan C/C++ Programs & notes-20102"
(added first notes to my notes page) |
(No difference)
|
Revision as of 21:34, 4 June 2010
pointer to functions
A pointer can be used to point to anything. Therefore you can also use it to point to a function, here’s an simple c program that uses pointer to function:
#include<stdio.h> void windows(char,int); void mac(char,int); int main(void) { void (*platform)(char,int); /* this a declaration of a function pointer with a argument of char and int*/ char name[30]; int option; printf("Please enter your name: "); scanf("%s", &name); do{ printf("Which platform 1.Windows, 2.Mac:"); scanf("%d", &option); platform = (option < 2) ? windows : mac; /* this line assign where the platform pointer should point to.*/ (option > 2||option<1) && printf("error: pick 1 or 2\n"); /*Lazy Evaculation*/ }while(option<1||option>2); platform(name , option); return 0; } void windows(char* str,int n) { printf("%s you've choosen option %d, you are a Windows user.\n",str,n); } void mac(char* str,int m) { printf(" %s you've chosen Option %d, you are Mac user.\n",str, m); }
In this program two functions are declared: void Windows(char *str,int n) and void Mac(char *str ,int m) they both return void. But the output a line. Within the main() a void pointer call platform is declared with two arugments( char, int) which are values types that will be pasted to the corrsponding functions which is determine by this line : platform = (option < 2) ? windows : mac;
If the user chooses option 1 platform will be set to point to the windows function else Mac fun ction otherwise. To call the function, you would call it using the pointer platform by use a line: platform(name , option); this line will call the function.