我正在学习C并且正在研究函数。因此,我读到实现自己的函数时,必须在main()之前声明它。如果我错过了声明,编译器将收到一条错误消息。
在我研究此示例时(发现数字是否为质数),
#include <stdio.h>
void prime(); // Function prototype(declaration)
int main()
{
int num, i, flag;
num = input(); // No argument is passed to input()
for(i=2,flag=i; i<=num/2; ++i,flag=i)
{
flag = i;
if(num%i==0)
{
printf("%d is not prime\n", num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime\n", num);
return 0;
}
int input() /* Integer value is returned from input() to calling function */
{
int n;
printf("\nEnter positive enter to check: ");
scanf("%d", &n);
return n;
}
我注意到已经声明了函数prime(),但主要是调用了函数input(),并在底部实现了函数input()。好的,我认为这是一个错误,我将名称从prime更改为input。
但是,如果删除了声明,但未在其中放置任何内容,则该程序将正确编译,并且运行平稳。(我在Ubuntu上编译并运行它。)
是否有必要声明不带参数的void函数?
如果在使用位置之前没有函数的前向声明,则编译器将为您创建带符号的隐式声明int input()
。它将使用您调用的函数的名称,并假定该函数正在返回int
,并且可以接受任何参数(如Bartek在注释中指出的)。
对于此函数,隐式声明与真实声明匹配,因此您没有问题。但是,您应对此始终保持谨慎,并且始终应首选使用前向声明,而不要使用隐式声明(无论它们是否相同)。因此,不仅要对void prime()
函数进行正向声明(假设您将在某处使用它),还应该对进行正向声明int input()
。
要查看如何传递任意数量的参数,请考虑以下事项:
#include <stdio.h>
// Takes any number of the arguments
int foo();
// Doesn't takes any arguments
int bar(void)
{
printf("Hello from bar()!\n");
return 0;
}
int main()
{
// Both works
// However, this will print junk as you're not pushing
// Any arguments on the stack - but the compiler will assume you are
foo();
// This will print 1, 2, 3
foo(1, 2, 3);
// Works
bar();
// Doesn't work
// bar(1, 2, 3);
return 0;
}
// Definition
int foo(int i, int j, int k)
{
printf("%d %d %d\n", i, j, k);
return 0;
}
因此,在函数定义中,您正在描述函数参数。但是,函数的声明告诉编译器不要对参数进行任何检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句