正确的C函数参数变量定义位置

时间:2016-08-24 17:38:02

标签: c

我总是在main()之前声明函数。令我困惑的是声明,定义,分配和传递函数参数的正确(或至少是最佳实践)方法。例如,这有效:

// 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!

2 个答案:

答案 0 :(得分:0)

在前向声明中,您不需要仅提供参数的名称类型(您可以提供名称)。但这并不一定要与定义函数时相同。

在funciton定义中说void my_func(int i){..},此函数参数的类型为int,变量名称为i。您可以通过功能块内的变量名i访问它的值。

此外,没有重新声明变量,因为这些变量的范围仅限于功能块。

这些方法与其使用方式基本没有区别。

答案 1 :(得分:0)

这也可行:

void my_func(int);

在功能签名中,它不是关于参数的名称,而是关于类型

当您声明与参数

同名的外部变量时,有一些特殊规则
int idum1 = 1;

void my_func(int idum1)
{
  idum1++;
}

此处具有最本地范围的变量会递增,而不是外部。