Home >Backend Development >C++ >The role and usage of const in c++
const stands for immutability in C and is used to force a variable, function parameter, or class member to remain constant so that its value cannot be modified while the program is running. Specific usage includes: modifying variables to force immutability, such as const int my_age = 30;; modifying function parameters to pass immutable values, such as void print_name(const string& name);; modifying class members to declare immutable variables, such as class Person {public: const string name;};.
The role and usage of const in C
const is a keyword in C, which is used to modify variables , function or class member, indicating that its value is a constant, that is, it cannot be modified.
Function:
Usage:
Variables:
<code class="cpp">const int my_age = 30; // 声明一个不可变整型变量</code>
Function parameters:
<code class="cpp">void print_name(const string&amp; name); // 声明一个接受不可变字符串参数的函数</code>
Class members:
<code class="cpp">class Person { public: const string name; // 声明一个类中的不可变成员变量 };</code>
Note:
const int
, const string&
. const string&
(passing an immutable string passed by reference) or string& const
(immutable string passed by reference). The latter usage is less common. The above is the detailed content of The role and usage of const in c++. For more information, please follow other related articles on the PHP Chinese website!