C++变量存储的生命周期与作用域实例代码精讲

auto类型:非静态的局部变量存储类型都是auto,这些数据存储在栈区,不初始化变量的值时随机的。C++中的auto还可以自动推导类型。生命周期:块内 作用域:块内

程序:

#include <stdio.h>
void test(void);
int main() {
// auto存储类型
    auto b = 13;  // C++新功能,auto自动推导类型
        int a = 12;  // auto存储类型的局部变量,存储在函数栈帧中
        {
                int c = 11;
                printf("%d\n",a);
                printf("%d\n",c);
        }
        test();
        printf("%d\n",a);
    return 0;
}
void test(void) {
        int d = 13;  // auto存储类型的局部变量,存储在函数栈帧中
        printf("%d\n",d);
}

static类型:static静态存储类型的变量,可以作为局部变量和全局变量。作为全局变量的时候不能被外部文件所访问,静态变量只初始化一次,存储在静态区中。也可以用来修饰函数,这样外部文件无法调用该函数。生命周期:整个程序 作用域:全局静态文件内、局部块内

程序:局部静态变量

#include <stdio.h>
#include <windows.h>
void test(void);
int main() {
        test();
        test();
        // printf("%d", a);  static作为局部变量,外面是访问不了的
        system("pause");
        return 0;
}
// 局部静态变量,存储在静态区中
void test(void) {
        static int a = 11;  // 只会被初始化一次
        a++;
        printf("%d\n", a);
}

程序:全局静态变量

#include <stdio.h>
#include <windows.h>
void test(void);
static int b = 33;  // 全局静态变量,外部文件无法访问,存储在静态区中
int main() {
        test();
        printf("%d\n", b);
        system("pause");
        return 0;
}
void test(void) {
        printf("%d\n", b);
}

register类型:寄存器变量,存储在cpu中不在内存中,所以没有地址。可以加快计算机访问。但是在C++中如果一定要去访问寄存器变量那么寄存器变量会被降级成普通变量。寄存器变量不能作为全局变量

程序:

#include <stdio.h>
// register int b = 12;  寄存器变量没法作为全局变量
int main() {
// register变量没有地址
        register int a = 12;
        printf("%d",a);
        printf("%p", &a);  // 强制访问register变量,那么这个变量会变为auto类型
    for(register int i=0; i<1000; i++){  // 加快运行速度写法,但是没必要
    }
        return 0;
}

extern类型:可以访问外部文件中的全局变量,只要在本文件中的变量前加上extern表示他是个外部变量。

程序:

extern.h

#ifndef _EXTER_H_
#define _EXTER_H_
#include <stdio.h>
void test1();
#endif

extern_test.cpp

#include "exter.h"
int c = 44;
int d = 55;  // 这里不要写extern int d;这是错误的  ,也不要写成extern int d=55这个是对的但是不推荐
void test1() {
        printf("extern_test_c_addr:%p\n", &c);
        printf("extern_test_d_addr:%p\n", &d);
}

man.cpp

#include <stdio.h>
#include <windows.h>
#include "exter.h"
void test(void);
extern int d;  //  extern拿到其他文件变量并作为本文件的全局变量
int main() {
// extern拿到其他文件变量并作为本文件的局部变量
        extern int c;
        printf("c=%d\n",c);
        c = 12;
        printf("c=%d\n",c);
        printf("d=%d\n",c);
        test();
        test1();
        printf("extern_test_c_addr:%p\n", &c);
        printf("main_d_addr:%p\n", &d);
        system("pause");
        return 0;
}
void test(void) {
        printf("test d=%d\n",d);
        //printf("c=%d\n", c);  局部变量访问不了
}

原文地址:https://blog.csdn.net/qq_14824921/article/details/126804319