2017年3月2日 星期四

C 語言中的函數指標

ref.http://ccckmit.wikidot.com/cp:main

C 語言中的函數指標

#include <stdio.h>
int add(int a, int b)
{
return a+b;
}
int mult(int a, int b)
{
return a*b;
}
int main()
{
int (*op)(int a, int b);
op = add;
printf("op(3,5)=%d\n", op(3,5));
op = mult;
printf("op(3,5)=%d\n", op(3,5));
}



函數指標型態 -- (function pointer type) 用typedef 將函數指標宣告成一種型態

#include <stdio.h>
typedef int(*OP)(int,int);
int add(int a, int b) 
{
return a+b;
}
int mult(int a, int b) 
{
return a*b;
}
int main() 
{
OP op = add;
printf("op(3,5)=%d\n", op(3,5));
op = mult;
printf("op(3,5)=%d\n", op(3,5));
}



變動參數


#include <stdio.h>
#include <stdarg.h>
void printList(int head, ... ) 
{
va_list va;
va_start(va, head);
int i;
for(i=head ; i != -1; i=va_arg(va,int)) 
{
printf("%d ", i);
}
va_end(va);
}

int main( void ) 
{
printList(3, 7, 2, 5, 4, -1);
}

變動參數2

#include <stdio.h>
int debug(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
return vprintf(fmt, args);
}
int main() 
{
debug("pi=%6.2f\n", 3.14159);
}



陳鍾誠 (2010年09月01日),(網頁標題) C 語言結構中的位元欄位,(網站標題) 陳鍾誠的網站,取自 http://ccckmit.wikidot.com/cp:structbits ,網頁修改第 5 版。