我总是在main()之前声明函数。令我困惑的是声明,定义,分配和传递函数参数的正确(或至少是最佳实践)方法。例如,这个工程:正确的C函数参数变量定义位置
// EXAMPLE 1 //
int idum1 = 1;
void my_func(int); // Says the function's going to need an integer.
void main (void)
{
my_func(idum1);
}
void my_func(idum2) // Is this then declaring AND defining a local integer, idum2?
{
// Do stuff using idum2...
}
但这个工程太:
// EXAMPLE 2 //
int idum1 = 1;
void my_func(int idum2); //Is this declaring a variable idum2 local to my_func?
void main (void)
{
my_func(idum1);
}
void my_func(idum3) // A different variable or the same one (idum2) still works.
//Is this declaring idum3 as a local integer?
{ //What happened to idum2, still a viable integer in the function?
// Do stuff using idum3...
}
而且这个工程:
// EXAMPLE 3 //
int idum1 = 1;
void my_func(int idum2); // Declaring...
void main (void)
{
my_func(idum1);
}
void my_func(int idum2) //Declaring again. Different address as in function declaration?
//Same variable and address?
{
// Do stuff using idum2...
}
所以做到这一点:
// EXAMPLE 4 //
int idum1 = 1;
void my_func(int);
void main (void)
{
my_func(idum1);
}
void my_func(int idum2) //Yet another way that works.
{
// Do stuff using idum2...
}
我是一个自学成才的初学者,但我一直在吱吱嘎嘎并没有真正了解正确的方式以及幕后发生的事情。我只知道它有效(总是很危险)。
我的直觉说例4是最好的方法;告诉它它需要什么类型,然后在函数中将它声明为类型以便于编码和错误检查。我确信有这样或那样的理由,这取决于你想要做什么,但真的可以在这里使用一些指导。
我确实看到了示例3,但看起来多余,声明了一个变量两次。
有人可以解释或指向我的一篇文章,解释我试图在这里得到的东西的来龙去脉吗?几乎不知道我在问什么,iykwim。网络上的一切都如此碎片化。试过CodingUnit,但教程只是不够深入。 TIA!
'void main(void)'是宿主环境中的无效签名。 'main'将返回一个'int'结果。 – Olaf
如果这是“主要基于意见”,“太宽泛”或“寻求外部资源”,我真的很挣扎。无论如何,它在这里是无关紧要的。 – Olaf
看来你需要适当的知识。我的建议是去C的权威书籍清单。 –