函数原型声明

我正在练习c中的function并且遇到了程序….

#include int main() { float a=15.5; char ch ='C'; printit(a,ch); return 0; } printit(a,ch) { printf("%f\n%c",a,ch); } 

我想知道为什么上面的程序编译而不是给出我迄今为止所理解的错误是……

  1. 必须使用特定原型声明c中的函数(但此程序不包含原型)

  2. 为什么程序给char变量输出’x’?

  3. c中的函数是否能够接受该值而不被声明参数中的类型,如函数声明中所做的那样?

首先,C语言中没有要求在调用函数之前为函数提供原型。 在C99版本的语言中,需要在调用函数之前声明它,但仍然没有要求提供原型。

由于您的编译器没有抱怨,您必须使用C89 / 90编译器,而不是C99编译器。

其次,在C89 / 90中,当你调用一个未声明的函数时,你会传递类型为floatchar参数

 printit(a,ch); 

编译器将执行默认参数提升,并实际传递doubleint类型的值。 必须相应地定义您的函数才能使代码生效。 您将函数定义为

 printit(a, ch) { ... 

该定义意味着两个参数都具有int类型。 这违反了上述要求。 代码的行为未定义。 再进一步分析代码或猜测为什么它以打印方式打印出来的东西再也没有任何意义。 您的代码的行为再次未定义。

您(未声明的)函数的正确定义可能如下所示

 int printit(double a, int ch) { ... 

或者,它可以用K&R样式定义为

 printit(a, ch) float a; { ... 

这可能会使您的代码正常工作。 但是,更好的方法是在调用之前为printit提供原型。 您想要使用哪个原型 – void printit(double a, int ch)void printit(float a, char ch)或其他东西 – 供您void printit(float a, char ch)决定。

  1. 在C中,如果在使用之前没有定义函数,则编译器会推断出隐式定义
  2. 如果没有为函数参数或其返回值指定类型,则默认为int
  3. 你得到’x’,因为编译器使用ch参数作为整数。
  1. 当你从main调用printit()时,main需要知道printit。 解决这个问题的一种方法是在main上面定义printit。
  2. printf应打印“15.5”,然后打印换行符,然后打印“C”。
  3. 我对这个问题感到困惑。 printit()的声明应为void printit(float a,char ch);
 void printit(float a, char ch) { printf("%f\n%c",a,ch); } int main() { float a=15.5; char ch ='C'; printit(a,ch); return 0; }
void printit(float a, char ch) { printf("%f\n%c",a,ch); } int main() { float a=15.5; char ch ='C'; printit(a,ch); return 0; } 

该代码几乎肯定会读到:

 #include  void printit(float a, char ch); int main() { float a=15.5; char ch ='C'; printit(a,ch); return 0; } void printit(float a, char ch) { printf("%f\n%c\n",a,ch); } 

如果你想整齐地写它。 但是,要解决上述问题:

1)你应该包括一个原型,是的。 但是,由于您只编译一个单元(.c文件),编译器可以非常轻松地确定您的函数所在的位置,因此您的意思是什么。 我明白了:

 test.c:11: warning: conflicting types for 'printit' test.c:7: note: previous implicit declaration of 'printit' was here 

我强烈建议使用-Wall -Werror -pedantic进行编译,将这样的警告转换为错误并中止编译,强制您编写正确的代码,以便以后减少错误。

2)我在新线上得到15.5然后是C。 我不确定Z的来源。

3)您不必指定类型 – 但是,如果不这样做,如果类型不兼容,您将无法从编译器中获益。 一个非常常见的情况是将数据传递给汇编。 这不是严格需要的,但它可能违反了标准C,绝对不是最佳做法。

问题1: printit是在main之后定义的。解决方案是将函数原型放在顶部。 问题2:正确声明函数原型,(你没有编写返回和参数类型)解决方案:

 #include  void printit(float a, char ch); int main() { float a=15.5; char ch ='C'; printit(a,ch); return 0; } void printit(float a, char ch) { printf("%f\n%c",a,ch); }