c++ 在函数内使用全局变量会导致创建局部副本吗

6vl6ewon  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(138)

不幸的是,我找不到关于这个问题的任何东西,尽管我不敢相信这个问题以前没有被问过。
当我在函数中使用全局变量时,是用传递的参数创建变量的本地副本,还是直接访问全局变量?使用引用声明器&定义全局变量作为函数的参数还是指针*定义全局变量有意义吗?
PS:我知道全局变量是一个不好的实践,但我正在为微控制器编程,有时使用全局变量是有意义的。

bpsygsoo

bpsygsoo1#

全局变量在函数中使用时不会被复制。直接使用。例如:

  1. #include <stdio.h>
  2. int x;
  3. void foo1()
  4. {
  5. x=2;
  6. }
  7. void foo2()
  8. {
  9. printf("%d\n", x);
  10. }
  11. int main()
  12. {
  13. foo1();
  14. foo2();
  15. return 0;
  16. }

输出:

  1. 2

第一个函数修改x,第二个函数读取修改后的x并打印出来。
如果全局变量实际上被复制到每个函数中,那么就不可能修改它们,上面的代码将打印0

展开查看全部
sqyvllje

sqyvllje2#

当我在函数中使用全局变量时,是用传递的参数创建变量的本地副本,还是直接访问全局变量?
直接使用全局变量。不创建本地副本。
使用引用声明符将全局变量定义为函数的参数&或作为指针 * 是否有意义?
是的,在某些情况下,这可能是有意义的。例如,如果你有几个全局变量,并且有一个写这些全局变量的函数,但不总是写相同的全局变量,那么传递一个指针或引用到全局变量可能是有意义的。
在下面的代码块中,我创建了一个简单的示例程序,它定义了三个全局变量abc,首先交换变量ab的值,然后交换变量bc的值。对于两个交换,可以使用相同的函数,因为该函数将指向要交换的每个全局变量的指针作为函数参数。

  1. #include <stdio.h>
  2. int a = 5;
  3. int b = 3;
  4. int c = 2;
  5. void swap( int *first, int *second )
  6. {
  7. int temp = *first;
  8. *first = *second;
  9. *second = temp;
  10. }
  11. int main( void )
  12. {
  13. printf(
  14. "Before swapping,\n"
  15. "the global variables have the following values:\n"
  16. "a = %d\nb = %d\nc = %d\n\n",
  17. a, b, c
  18. );
  19. swap( &a, &b );
  20. printf(
  21. "After swapping the values of a and b,\n"
  22. "the global variables have the following values:\n"
  23. "a = %d\nb = %d\nc = %d\n\n",
  24. a, b, c
  25. );
  26. swap( &b, &c );
  27. printf(
  28. "After also swapping the values of b and c,\n"
  29. "the global variables have the following values:\n"
  30. "a = %d\nb = %d\nc = %d\n\n",
  31. a, b, c
  32. );
  33. }

此程序具有以下输出:

  1. Before swapping,
  2. the global variables have the following values:
  3. a = 5
  4. b = 3
  5. c = 2
  6. After swapping the values of a and b,
  7. the global variables have the following values:
  8. a = 3
  9. b = 5
  10. c = 2
  11. After also swapping the values of b and c,
  12. the global variables have the following values:
  13. a = 3
  14. b = 2
  15. c = 5

因为你同时用C和C标记了这个问题(通常不应该这样做),所以我给出了一个与C和C兼容的例子。在C++中,通常使用引用而不是指针,并且使用std::cout而不是printf

展开查看全部

相关问题