开发者

const variable paradox

if I have some expression on c++:

const int x = 3;

can I say that x is a variable? It seems very strange cause x is not variable cause I can't change it, thanks in advance for any expanations

Edited P.S. thanks for all answers, I understood开发者_开发问答 that by definition of C++, answer for my question may be yes, do You know some other languages, in which the answer for my question will be no?


Yes. x is a variable, even though you cannot (legitimately) change its value.

Effectively, in C++, an object that has a name is a "variable."


This is philosophical , it cannot be modifiable, in fact some compiler like GCC stores it in the Text-section. So or is a non-modifiable variable, or a constant.


In C++ terminology the term variable is almost synonymous with the term object: any declared object is a variable. Whether the object is changeable or not makes no difference. So, within the official terminology yes, x is a variable.


In the ISO language definition for C++ such an object is referred to as a const variable, meaning a read-only variable. In conceptual terms and in natural language semantics it is a nonetheless constant.

I imagine the term is merely used to differentiate a constant object (such as x in your example) from a literal constant, (such as 3), where one is an addressable object, and the other is not. The term const object is not used because an object refers to the instance in memory, while a variable refers a name or identifier associated with an object.


BTW it is useful for a function declaration, for example

void ReadStuff(const int a)

This means that you actually can give the function a non static variable but it will be treated as a constant (ie. the function will not change it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜