874

1、所有函数外部定义的变量称为全局变量,其默认功能域从定义变量的位置到源文件的结束都是有效的。

2、如果需要使用全局变量,最好定义在文件的顶部,这样文件中的所有函数都可以直接使用。

实例

#include<stdio.h>
voidfunc1(){
x+=10;
y+=20;
printf("函数:%s中x=%dy=%d\n",__FUNCTION__,x,y);



intx=10;
inty=20;

voidfunc2(){
x+=10;
y+=20;
printf("函数:%s中x=%dy=%d\n",__FUNCTION__,x,y);


intmain(){

func1();
func2();
printf("函数:%s中x=%dy=%d\n",__FUNCTION__,x,y);

return0;

/*
输出:

main.cpp:Infunction‘voidfunc1()’:
main.cpp:6:5:error:‘x’wasnotdeclaredinthisscope
6|x+=10;
|^
main.cpp:7:2:error:‘y’wasnotdeclaredinthisscope
7|y+=20;
|^

*/

以上就是c语言中全局变量的使用,希望对大家有所帮助。更多C语言学习指路:C语言教程

发表回复