在函数本身而不是在主函数中声明由参数限定的变量有什么问题?

what is the problem with declaring a variable bounded by a parameter in the function itself rather than in the main function?

本文关键字:函数 变量 问题 什么 参数 声明      更新时间:2023-10-16

我一直试图在函数本身中包含变量的声明,但除非我将其包含在主函数中,否则它不起作用。为什么会这样?

#include<iostream>
using namespace std;

function1(int x)
{
int x =1;
cout << x << endl;
return 0;
}
int main ()
{
function1( x);
return 0;
}`  `

欢迎来到C++编码的世界!看起来这里的代码中存在很多问题 - 让我们分解一下,看看我们能找到什么。

首先,为了回答您最初的问题,您对 x(在function1中(的声明是在您尝试使用变量的函数(在main中(之外进行的。C++通常看不到你在一个函数中声明的变量,当它在另一个函数中运行时;这是设计使然,称为范围。

首先,由于多种原因,代码无法编译,首先是最后代码中存在杂散反引号。这些需要删除。

int main ()
{
function1( x);
return 0;
}`  `  //<-- the `  ` will make the compiler angry

现在让我们看一下导致错误的原因:x 尚未声明。在C++中,变量必须先"声明",然后才能使用。由于"x"在function( x);中使用之前没有被声明,编译器会把它踢回来,因为它不知道"x"是什么意思。试试这个:

int x = 0;
function1( x);

不过,我们还没有完全完成。一旦我们进行了此更改,编译器将抛出另一个错误:In function 'int function1(int)': 8:5: error: declaration of 'int x' shadows a parameter.您已经在函数 1 的定义中包含了一个 int x;通过在 function1 中创建另一个int x,您已经蒸蒸了原始x。让我们将其从定义更改为赋值。

function1(int x)
{
x =1;
cout << x << endl;
return 0;
}

越来越糟糕,但我们还有一个错误:6:16: error: ISO C++ forbids declaration of 'function1' with no type [-fpermissive].这是告诉你function1需要一个返回类型,这是函数名称前面的关键字,告诉编译器它返回什么类型的数据(如果它不返回任何数据类型void(。看起来您正在使用return 0;- 为什么不返回一个 int?

int function1(int x)

现在,我们终于有了可以编译和运行的代码。

#include<iostream>
using namespace std;

int function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
int main ()
{
int x = 0;
function1( x);
return 0;
}

试试这里!

祝你好运!

为什么会这样?

发生这种情况是因为x现在在main中使用它的上下文中未定义,并且它已经在您尝试在function1()中定义的上下文中定义(作为参数(。

在第一种情况下,您肯定会收到错误,因为main中使用的x是完全未定义的......编译器将查看该function1(x)调用,并想知道它应该为x提供什么。

在后一种情况下,编译器可能会允许您重新定义x,但它可能至少会发出警告。此外,如果允许,则无论您为x参数传入什么,您的function1()都将始终打印出1,因为将使用新声明的x而不是参数中传递的值。

您缺少的概念称为范围。每个变量都有一个作用域,它本质上是已知的领域。变量的作用域可以是全局的,在这种情况下,它可用于整个程序,或者仅限于单个文件,或者它可以在函数或块中声明,在这种情况下,它是该代码块的本地。

int x = 12;   // x is available anywhere in the file and has initial value 12
void foo(int x)
{
cout << x << endl;    // prints the value passed to foo by the caller
int x = 34;           // this new x hides the parameter and is available
//   anywhere inside this function, but not outside
cout << x << endl;    // prints the new x, i.e. 34
{
cout << x << endl;    // still prints 34
int x = 97;           // hides the previous x, available only within
//   this block or sub-blocks
cout << x << endl;    // prints 97
}                         // x from the enclosed block goes out of scope
cout << x << endl;    // prints 34, because we're back to the x at function scope
}

了解作用域非常重要,因为变量名称经常是有意或无意重复的,您需要能够分辨给定变量在作用域中的位置,因此可以使用有效,何时无效。