C局部变量与函数同名 - 它是如何工作的?

时间:2022-12-25 19:32:04

I teach C to absolute beginners and I have noticed that some of my students get the notion to use the same name for the function and a local variable in the function. I think it's goofy and would prevent recursion.

我教C给绝对的初学者,我注意到我的一些学生得到的概念是在函数中使用相同的名称和局部变量。我觉得这很傻,会阻止递归。

Here's an example:

这是一个例子:

int add2numbers (int a, int b) { /* Tested on Mac OS X with gcc */
    int add2numbers = a + b;
    return add2numbers;
}

The way I understand how it works is that the variable is in the local scope of the function, and the function is in the global scope.

我理解它是如何工作的方式是变量在函数的局部范围内,并且函数在全局范围内。

So, the questions...

所以,问题......

  1. Am I understanding this correctly?
  2. 我理解正确吗?
  3. Where the h*** are they getting that idea from?
  4. 他们从哪里得到这个想法?

Thanks

谢谢

3 个解决方案

#1


11  

You are correct in assuming that the function is global and the variable is local. That is the reason why there is no conflict in your program.

假设函数是全局的并且变量是本地的,那么你是正确的。这就是为什么你的程序没有冲突的原因。

Now consider the program given below,

现在考虑下面给出的程序,

#include<stdio.h>
int x=10;
void x()
{
  printf("\n%d",x);
}

int main()
{

   x();
   return 0; 
}

You will get an error because in this program both the function x() and variable x are global.

您将收到错误,因为在此程序中,函数x()和变量x都是全局的。

#2


4  

Pascal :)

帕斯卡尔:)

Simple function in Pascal:

Pascal的简单功能:

function max(num1, num2: integer): integer;
   var
   (* local variable declaration *)
   result: integer;
begin
   if (num1 > num2) then
      result := num1
   else
      result := num2;
   max := result;
end;

#3


0  

1) Am I understanding this correctly?

1)我是否理解正确?

Pretty much.

差不多。

2) Where the h*** are they getting that idea from???

2)他们从哪个h ***得到了这个想法?

Not a constructive question for SO.

对SO来说不是一个建设性的问题。

#1


11  

You are correct in assuming that the function is global and the variable is local. That is the reason why there is no conflict in your program.

假设函数是全局的并且变量是本地的,那么你是正确的。这就是为什么你的程序没有冲突的原因。

Now consider the program given below,

现在考虑下面给出的程序,

#include<stdio.h>
int x=10;
void x()
{
  printf("\n%d",x);
}

int main()
{

   x();
   return 0; 
}

You will get an error because in this program both the function x() and variable x are global.

您将收到错误,因为在此程序中,函数x()和变量x都是全局的。

#2


4  

Pascal :)

帕斯卡尔:)

Simple function in Pascal:

Pascal的简单功能:

function max(num1, num2: integer): integer;
   var
   (* local variable declaration *)
   result: integer;
begin
   if (num1 > num2) then
      result := num1
   else
      result := num2;
   max := result;
end;

#3


0  

1) Am I understanding this correctly?

1)我是否理解正确?

Pretty much.

差不多。

2) Where the h*** are they getting that idea from???

2)他们从哪个h ***得到了这个想法?

Not a constructive question for SO.

对SO来说不是一个建设性的问题。