Home >Backend Development >C++ >The role of extern, static and mutable in C++ function declarations: understanding their semantics and effects
The keyword function extern refers to functions in other source files static limits the scope of the function to the current source file mutable allows objects declared as const to be modified within the function
C The roles of extern, static and mutable in function declarations: understanding their semantics and effects
In C, the extern, static and mutable keywords in function declarations have different semantics and effect.
extern
Example:
// header.h extern int add(int a, int b); // source1.cpp #include "header.h" int main() { int sum = add(1, 2); return 0; }
In source1.cpp, the extern keyword allows reference to the add function declared in header.h without including the add function Definition.
#static
Example:
// source1.cpp static int localFunction() { return 10; } int main() { int x = localFunction(); // 可以访问 localFunction return 0; }
Due to the static keyword, localFunction can only be accessed in source1.cpp and not in other source files.
mutable
Example:
// source1.cpp class MyClass { public: const int x = 10; // 不可变数据成员 mutable int y = 20; // 可变数据成员 }; void modifyConst(MyClass& obj) { obj.y++; // 允许修改 y,因为 y 是 mutable }
Due to the mutable keyword, the modifyConst function can modify the y data member of the MyClass class, even if y is const.
Understanding the semantics and effects of these keywords is critical to writing robust and efficient C programs.
The above is the detailed content of The role of extern, static and mutable in C++ function declarations: understanding their semantics and effects. For more information, please follow other related articles on the PHP Chinese website!