全局和局部范围变量(为什么第二个打印输出 28 在这里?)

Global and Local Scope Variables ( Why is the 2nd printout 28 here? )

#include <stdio.h>

int i = 3, j = 10;

int crypt(int j)
{
  return (i = i+j);
}

void decrypt(int x, int i)
{
  j += crypt(i);
}

int main(void)
{
  int i = 0;
  i = crypt(5);
  decrypt(i, j);
  printf("|%d %d|", i, j);
  return 0;
}

我无法弄清楚为什么打印输出 |8 28|。

“8”部分,我理解为

i = crypt(5) -> j 在这个函数中现在是 5 -> i = i + j -> 没有 i 因此它使用全局变量 i = 3 -> i = 3 + 5 -> return我=8

所以main函数中的i变成了8.

但是下一个打印输出呢?为什么是 28 而不是 23?

我是这样读的

decrypt(i, j) -> decrypt(8, 10) -> x 现在是 8,i 现在是 10 在这个函数中 -> j += crypt(i) -> j += crypt(10 ) -> 此函数中的 j 现在为 10。

return ( i = i + j ), 这个函数里没有 i 所以 i = 3 + 10... returns 13?

那么j += 13就是23?

我把步骤的哪一部分搞砸了?我一直在在线阅读本地/全球范围的内容,但我仍然不太明白我哪里出错了……感觉我在某个地方弄乱了我对 i 的价值。

PS:对于格式不佳,我深表歉意,我不太确定我还能怎样把它写得干净利落。

你写:

return ( i = i + j ), there's no i in this function so i = 3 + 10... returns 13?

不,i 不再是 3。由于 crypt

的第一次调用,之前已更改为 8,即此处 return (i = i+j);

当你写:

So the i in the main function becomes 8.

它是正确的,但全局 i 也被更改了。

这里有一个全局 i 和 j,以及一个局部 i 变量。总的来说,当你提到 i 时,它首先会检查你当前的范围——所以任何更改都会在你的本地 i 上进行,而全局 i 不会改变。如果你要求 main 之外的一个函数用 i var 做一些事情,它首先检查它自己的范围,然后检查全局 i var。在这种情况下,将在全局 i.

上进行更改

所以..第一次-

local i在main中设置,然后接收i = crypt(5)的值;另一件事是,在这个函数中你还把 8 的值赋给了全局的 i-> (i = i+j),然后把 8 的值返回给局部的 i.

第二个函数:

解密(i, j);在这里,您将本地 i(= 8) 和全局 j(=10) 发送到该函数,其中您有:

j += crypt(i);
这给你 j= j+((global) i = 8 + 10): 10+8+10。并将你的全局 i 设置为 18.

Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a funcion, and can be used only inside that function. It is possible to have local variables with the same name in different functions.

在第一次调用函数 crypt(5); 时,您已将全局变量值修改为,

i = i+j ----> i = 3+5 ----> i=8

并且当调用decrypt()函数时,i=8 因为 i 是 8 j 在 additon 之后打印 28 这是一个全局变量 .

You can see how memory is allocated in C

考虑以下版本的代码,其中变量已重命名以避免任何混淆。

#include <stdio.h>

int iGlobal = 3, jGlobal = 10;

int crypt(int jParam)
{
  return (iGlobal = iGlobal+jParam);
}

void decrypt(int xUnused, int iParam)
{
  jGlobal += crypt(iParam);
}

int main(void)
{
  int iLocal = 0;
  iLocal = crypt(5);
  decrypt(iLocal, jGlobal);
  printf("|%d %d|", iLocal, jGlobal);
  return 0;
}

现在,解释执行代码时发生的事情应该相对容易了:

  1. main()中,iLocal被zet为0
  2. main 呼叫 crypt(5)
  3. crypt计算iGlobal+jParam,即3+5,并将结果赋值给iGlobal,即iGlobal为8
  4. crypt returns 8
  5. main 将 return 值 8 分配给 iLocal
  6. main 呼叫 decrypt(8,10)
  7. decrypt 呼叫 crypt(10)
  8. crypt计算iGlobal+jParam,即8+10,并将结果赋值给iGlobal,即iGlobal为18
  9. crypt returns 18
  10. decrypt 将 18 的 return 值加到 jGlobal 上,即 jGlobal 是 28
  11. printf 打印 iLocal、8 和 jGlobal、28
  12. 的值

复杂的部分(如果有的话)是知道全局变量何时被其本地变量替换(a.k.a。隐藏或隐藏),答案是 "whenever possible"。