# c prototype ### 重點 在c語言當中 declaration千萬不要使用f() //not define prototype compiler並不知道這個函數的參數是什麼 因此參數可以自己在definition的時候才寫, 但這樣很危險 compiler會預設把int, short, char 轉成int, float跟double轉成double 如果用declaration的參數用錯, ex:char用成double接,會是undefined behaviour 建議還是不要這樣用,太危險 建議還是要用f(void) //define parameter is void - c++ 預設 f() 等價於 f(void),即此函式不帶參數, 故避免了危險的發生 下面是幾個例子 ```c= #include <stdio.h> //no declare prototype is very dangerous int f(); int f1(); int f2(); //int f(double ,double , double); //int f1(int, int, int); //int f2(int,int , double); int main(){ int a = 5; char k = 'a'; float t = 10.0f; //By default, int,char,float will change to int //and float, double will change to double f(a,k,t); f1(a,k,t); f2(a,k,t); } //correct version int f2(int a, int b, double c){ printf("---------------------f2 correct function\n"); printf("%d\n",a); printf("%d\n",b); printf("%lf\n",c); printf("%lf\n",a+b+c); return a+b+c; } //int a, int b is correct type, but int c is wrong //therefore, a and b has been set correct value, but the value of c is undefined behaviour //i am not sure that the value of a,b will always be correct value.... int f1(int a, int b, int c){ printf("---------------------f1 function\n"); printf("%d\n",a); printf("%d\n",b); printf("%d\n",c); printf("%lf\n",a+b+c); return a+b+c; } //double a, double b is wrong type, but c is wrong //however, all three value is undefined behaviour int f(double a, double b, double c){ printf("%lf\n",a); printf("%x\n", a); printf("%lf\n",b); printf("%x\n", b); printf("%lf\n",c); printf("%lf\n",a+b+c); return a+b+c; } ``` output= ![](https://i.imgur.com/18K2Uc2.png) ```c= #include <stdio.h> //int f(); //int f1(); //int f2(); int f(double ,double , double); int f1(int, int, int); int f2(int,int , double); int main(){ int a = 7; char k = 'b'; float t = 11.0f; f((double)a,(double)k,(double)t); f(a,k,t); f1(a,k,t); f2(a,k,t); } int f2(int a, int b, double c){ printf("---------------------f2 correct function\n"); printf("%d\n",a); printf("%d\n",b); printf("%lf\n",c); printf("%lf\n",a+b+c); return a+b+c; } int f1(int a, int b, int c){ printf("---------------------f1 function\n"); printf("%d\n",a); printf("%d\n",b); printf("%d\n",c); printf("%lf\n",a+b+c); return a+b+c; } int f(double a, double b, double c){ printf("---------------------f function\n"); printf("%lf\n",a); printf("%x\n", a); printf("%lf\n",b); printf("%x\n", b); printf("%lf\n",c); printf("%lf\n",a+b+c); return a+b+c; } ``` output= ![](https://i.imgur.com/oUS1goP.png) ###### tags: `C` `prototype`