C的函数宣言和形参
C的函数声明和形参
<1>函数声明
最近看C语言,很迷惑,有些地方有函数声明有些地方没有。
查了下教材,做下小结,笔抄写一遍,网上记一遍,备忘!
有以下三种情况不用函数声明,可以直接调用:
1.被调函数返回类型为整形或者char型,系统会自理。
举例:
//代码1 #include <stdio.h> int main(){ int a=30; double d=4.4334; printf("a=%d",call(a)); return 0; } int call(int d){ printf("HelloWorld\n"); return d; }
正确。如果将call函数的返回类型改为double呢?
//代码2 #include <stdio.h> int main(){ int a=30; double d=4.4334; printf("d=%f",call(d)); return 0; } double call(double d){ printf("HelloWorld\n"); return d; }
gcc表示对call函数的类型很迷惑很纠结~
D:\prj\core_c>gcc demo.c -o demo.out demo.c:8:8: error: conflicting types for 'call' demo.c:5:16: note: previous implicit declaration of 'call' was here
2.被调函数定义在主函数之前。
上面的代码2的call方法在在main之前,就不会有问题了。
3.在定义所有函数之前,先对调用函数做了声明。
//代码4 #include <stdio.h> double call(double d); int main(){ int a=30; double d=4.4334; printf("d=%f",call(d)); return 0; } double call(double d){ printf("HelloWorld\n"); return d; }
相当于做了外部声明。
<2>形参。
举例:
(1)函数的声明,可以省去变量名。
int getMax(int a,int b); //可以省去变量名,方便编译系统差错: int getMax(int,int);
(2).宏定义时候的形参不需要类型,不用给它分配内存。
#define P(d) printf("%d",d)
初学者笔记。