gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:58:03 24 4
gpt4 key购买 nike

我总是在 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!

最佳答案

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

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

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

这些方法基本上没有区别,只是约定俗成的使用方式。

关于c - 正确的 C 函数参数变量定义位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129735/

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