gpt4 book ai didi

c - 函数原型(prototype)声明

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:09 24 4
gpt4 key购买 nike

我正在练习 c 中的函数并接触到程序....

#include<stdio.h>

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中的函数必须用特定的原型(prototype)声明(但本程序不包含原型(prototype))

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

  3. c 中的函数是否能够像在函数声明中所做的那样在不声明参数类型的情况下接受值?

最佳答案

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

由于您的编译器没有报错,您使用的一定是 C89/90 编译器,而不是 C99 编译器。

其次,在 C89/90 中,当您像在

printit(a,ch);

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

printit(a, ch)  
{
...

该定义意味着两个参数的类型都是 int。这违反了上述要求。您的代码的行为未定义。进一步分析代码或猜测为什么它以这种方式打印某些内容不再有意义。您的代码的行为再次未定义。

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

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

或者,它可以在 K&R 风格中定义为

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

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

关于c - 函数原型(prototype)声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com