我们可以在C中的main函数中定义函数原型吗?

Adi*_*aya 4 c prototype

在我的大学,我们的老师教我们"我们在主要功能之前定义功能原型.喜欢:

#include<stdio.h>
void findmax(float, float);
int main()
{
    //code goes here
}
Run Code Online (Sandbox Code Playgroud)

但今天我的朋友告诉我他们学会了将原型放在主要功能中.喜欢:

#include<stdio.h>
int main()
{
    void findmax(float, float);

    float firstnum, secondnum;

    printf("Enter first:");
    scanf("%f", &firstnum);

    printf("Enter second:");
    scanf("%f", &secondnum);

    findmax(firstnum, secondnum);
}

void findmax(float x, float y)
{
    float maxnum;

    if(x>y)
    {
            maxnum=x;
    }

    else
    {
       maxnum=y;
    }

    printf("The max is %f", maxnum);
}
Run Code Online (Sandbox Code Playgroud)

它们都有效.我想知道它们之间是否存在差异.谢谢.

hac*_*cks 5

我们可以在C中的main函数中定义函数原型吗?

是.

我想知道他们之间是否存在差异

不同之处在于,第一个片段原型是全局的,而第二个是原生的main.findmax在其声明和/或定义后将可见.

#include<stdio.h>
void foo();
int main()
{
    void findmax(float, float); 
    foo();
    findmax(10, 20);  // It knows findmax by the prototype declared above
}

void findmax(float x, float y)
{
    float maxnum;

    if(x>y)
        maxnum=x;
    else
        maxnum=y;

    printf("The max is %f", maxnum);
}

void foo(){   // foo is using findmax after its definition.
    findmax(12, 30);
}
Run Code Online (Sandbox Code Playgroud)

  • 但至关重要的是,在`main`和`findmax`之间定义的函数`bar`将*不能引用`findmax`(或者更确切地说,它将假设一个隐式声明,在这种情况下将是不兼容的). (2认同)