不幸的是,我找不到关于这个问题的任何东西,尽管我不敢相信这个问题以前没有被问过。当我在函数中使用全局变量时,是用传递的参数创建变量的本地副本,还是直接访问全局变量?使用引用声明器&定义全局变量作为函数的参数还是指针*定义全局变量有意义吗?PS:我知道全局变量是一个不好的实践,但我正在为微控制器编程,有时使用全局变量是有意义的。
&
*
bpsygsoo1#
全局变量在函数中使用时不会被复制。直接使用。例如:
#include <stdio.h>int x;void foo1(){ x=2;}void foo2(){ printf("%d\n", x);}int main(){ foo1(); foo2(); return 0;}
#include <stdio.h>
int x;
void foo1()
{
x=2;
}
void foo2()
printf("%d\n", x);
int main()
foo1();
foo2();
return 0;
输出:
2
第一个函数修改x,第二个函数读取修改后的x并打印出来。如果全局变量实际上被复制到每个函数中,那么就不可能修改它们,上面的代码将打印0。
x
0
sqyvllje2#
当我在函数中使用全局变量时,是用传递的参数创建变量的本地副本,还是直接访问全局变量?直接使用全局变量。不创建本地副本。使用引用声明符将全局变量定义为函数的参数&或作为指针 * 是否有意义?是的,在某些情况下,这可能是有意义的。例如,如果你有几个全局变量,并且有一个写这些全局变量的函数,但不总是写相同的全局变量,那么传递一个指针或引用到全局变量可能是有意义的。在下面的代码块中,我创建了一个简单的示例程序,它定义了三个全局变量a,b和c,首先交换变量a和b的值,然后交换变量b和c的值。对于两个交换,可以使用相同的函数,因为该函数将指向要交换的每个全局变量的指针作为函数参数。
a
b
c
#include <stdio.h>int a = 5;int b = 3;int c = 2;void swap( int *first, int *second ){ int temp = *first; *first = *second; *second = temp;}int main( void ){ printf( "Before swapping,\n" "the global variables have the following values:\n" "a = %d\nb = %d\nc = %d\n\n", a, b, c ); swap( &a, &b ); printf( "After swapping the values of a and b,\n" "the global variables have the following values:\n" "a = %d\nb = %d\nc = %d\n\n", a, b, c ); swap( &b, &c ); printf( "After also swapping the values of b and c,\n" "the global variables have the following values:\n" "a = %d\nb = %d\nc = %d\n\n", a, b, c );}
int a = 5;
int b = 3;
int c = 2;
void swap( int *first, int *second )
int temp = *first;
*first = *second;
*second = temp;
int main( void )
printf(
"Before swapping,\n"
"the global variables have the following values:\n"
"a = %d\nb = %d\nc = %d\n\n",
a, b, c
);
swap( &a, &b );
"After swapping the values of a and b,\n"
swap( &b, &c );
"After also swapping the values of b and c,\n"
此程序具有以下输出:
Before swapping,the global variables have the following values:a = 5b = 3c = 2After swapping the values of a and b,the global variables have the following values:a = 3b = 5c = 2After also swapping the values of b and c,the global variables have the following values:a = 3b = 2c = 5
Before swapping,
the global variables have the following values:
a = 5
b = 3
c = 2
After swapping the values of a and b,
a = 3
b = 5
After also swapping the values of b and c,
b = 2
c = 5
因为你同时用C和C标记了这个问题(通常不应该这样做),所以我给出了一个与C和C兼容的例子。在C++中,通常使用引用而不是指针,并且使用std::cout而不是printf。
std::cout
printf
2条答案
按热度按时间bpsygsoo1#
全局变量在函数中使用时不会被复制。直接使用。例如:
输出:
第一个函数修改
x
,第二个函数读取修改后的x
并打印出来。如果全局变量实际上被复制到每个函数中,那么就不可能修改它们,上面的代码将打印
0
。sqyvllje2#
当我在函数中使用全局变量时,是用传递的参数创建变量的本地副本,还是直接访问全局变量?
直接使用全局变量。不创建本地副本。
使用引用声明符将全局变量定义为函数的参数&或作为指针 * 是否有意义?
是的,在某些情况下,这可能是有意义的。例如,如果你有几个全局变量,并且有一个写这些全局变量的函数,但不总是写相同的全局变量,那么传递一个指针或引用到全局变量可能是有意义的。
在下面的代码块中,我创建了一个简单的示例程序,它定义了三个全局变量
a
,b
和c
,首先交换变量a
和b
的值,然后交换变量b
和c
的值。对于两个交换,可以使用相同的函数,因为该函数将指向要交换的每个全局变量的指针作为函数参数。此程序具有以下输出:
因为你同时用C和C标记了这个问题(通常不应该这样做),所以我给出了一个与C和C兼容的例子。在C++中,通常使用引用而不是指针,并且使用
std::cout
而不是printf
。