LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 196|回复: 0

C++extern 存储类

[复制链接]
发表于 2024-1-7 14:27:30 | 显示全部楼层 |阅读模式
extern 存储类只是告诉我们变量是在其他地方定义的,而不是在使用它的同一块中(即外部链接)。基本上,该值在不同的块中分配给它,也可以在不同的块中覆盖/更改。extern 变量只不过是一个使用合法值初始化的全局变量,在该变量中声明它以便在其他地方使用。

普通全局变量也可以通过在任何函数/块中的声明/定义之前放置“extern”关键字来使其成为 extern。使用 extern 变量的主要目的是可以在两个不同的文件之间访问它们,这两个文件是大型程序的一部分。

extern 存储类对象的属性

范围:全球
默认值:零
内存位置:RAM
生命周期:直到计划结束。
extern 存储类示例

// C++ Program to illustrate the extern storage class
#include <iostream>
using namespace std;

// declaring the variable which is to
// be made extern an initial value can
// also be initialized to x
int x;
void externStorageClass()
{

    cout << "Demonstrating extern class\n";

    // telling the compiler that the variable
    // x is an extern variable and has been
    // defined elsewhere (above the main
    // function)
    extern int x;

    // printing the extern variables 'x'
    cout << "Value of the variable 'x'"
         << "declared, as extern: " << x << "\n";

    // value of extern variable x modified
    x = 2;

    // printing the modified values of
    // extern variables 'x'
    cout << "Modified value of the variable 'x'"
         << " declared as extern: \n"
         << x;
}

int main()
{

    // To demonstrate extern Storage Class
    externStorageClass();

    return 0;
}

输出

Demonstrating extern class
Value of the variable 'x'declared, as extern: 0
Modified value of the variable 'x' declared as extern:
2

有关外部变量如何工作的更多信息,请查看此链接。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表