← 返回首页
C语言系列教程 (二十三)
发表时间:2021-03-27 15:15:18
全局变量/局部变量/常量

1.局部变量

定义在函数内部的变量称为局部变量(Local Variable),它的作用域仅限于函数内部, 离开该函数后就是无效的,再使用就会报错。

#include <stdio.h>
#include <stdlib.h>

void fn(){
   int x = 100;

}

int main() {
    printf("x=%d\n",x); //错误,未定义x 
    return 0;
}

2.全局变量

在所有函数外部定义的变量称为全局变量(Global Variable),它的作用域默认是整个程序,也就是所有的源文件,包括 .c 和 .h 文件。

#include <stdio.h>
#include <stdlib.h>

int x = 10;
void fn(){
   int x = 100;
   printf("x=%d\n",x);
}

int main() {
    fn();
    printf("x=%d\n",x); //输出全局变量x 
    return 0;
}

运行结果:

x=100
x=10

fn函数可以直接访问全局变量x.例如:

#include <stdio.h>
#include <stdlib.h>
int x = 10;
void fn(){
   x++;
   printf("x=%d\n",x);
}


int main() {
    fn();
    printf("x=%d\n",x); //输出全局变量x 
    return 0;
}

运行结果:

x=11
x=11

如果全局变量x定义在fn函数之后,那么fn里如果要使用全局变量x,必须使用extern修饰。例如:

#include <stdio.h>
#include <stdlib.h>


void fn(){
   extern int x;    
   x = 100;
   printf("x=%d\n",x);
}

int x = 10;
int main() {
    fn();
    printf("x=%d\n",x); //输出全局变量x 
    return 0;
}

运行结果:

x=100
x=100

在代码块里(一对花括号)也可以定义局部变量。例如:

#include <stdio.h>
#include <stdlib.h>

int x = 10;
void fn(){
   int x = 100;
   printf("x=%d\n",x);
}

int main() {
    fn();
    {
        int x = 1000;
    printf("x=%d\n",x);  //输出代码块变量x 
    }
    printf("x=%d\n",x);//输出全局变量x 
    return 0;
}

运行结果:

x=100
x=1000
x=10

3.常量

使用const修饰的称为常量,常量值不能改变。

#include <stdio.h>
#include <stdlib.h>

void fn(){
   const int x = 100;
   printf("x=%d\n",x++); //错误,常量不能改变。
}