fork download
  1. #include <stdio.h>
  2.  
  3. // 全局变量
  4. int x = 0;
  5.  
  6. void mondai1() {
  7. x = 102; // 修改全局变量
  8. printf("x = %d ← 在mondai1内更新全局变量\n", x);
  9. }
  10.  
  11. void mondai2() {
  12. static int c = 0; // 静态变量,只初始化一次
  13. c += 4;
  14. x = c + 1; // 更新全局变量(教材最后一行=13 就是因为这里)
  15. }
  16.  
  17. int main() {
  18. printf("x = %d ← 全局变量x的初始值\n", x);
  19.  
  20. x = 101; // 更新全局变量
  21. printf("x = %d ← 全局变量x在第18行更新\n", x);
  22.  
  23. mondai1(); // 调用函数mondai1
  24.  
  25. // 调用3次mondai2
  26. mondai2();
  27. mondai2();
  28. mondai2();
  29. printf("x = %d ← mondai2执行3次后静态变量c累积并更新全局变量\n", x - 1);
  30.  
  31. // 定义局部变量x(会屏蔽全局x)
  32. int x = 103;
  33. printf("x = %d ← 局部变量x\n", x);
  34.  
  35. x = 104;
  36. printf("x = %d ← 局部变量x\n", x);
  37.  
  38. // 打印全局变量x
  39. {
  40. extern int x; // 显式指全局x
  41. printf("x = %d ← 全局变量x的值(在第12行更新过)\n", x);
  42. }
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
x = 0 ← 全局变量x的初始值
x = 101 ← 全局变量x在第18行更新
x = 102 ← 在mondai1内更新全局变量
x = 12 ← mondai2执行3次后静态变量c累积并更新全局变量
x = 103 ← 局部变量x
x = 104 ← 局部变量x
x = 13 ← 全局变量x的值(在第12行更新过)