const variable paradox - c++

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).

Related

Are references distinct types? [duplicate]

From what I can tell, references can be used wherever the original type can (I'm not implying the reverse is true), the only difference is their mutation semantics (when the variables are used as lvalues).
Wouldn't they then qualify as the same type as the original? If so, why is the fact that something is a reference, stored in its type?
Edit: if references are a different type, why can they be substituted for the original type in so many situations, without explicit casting? Is there implicit cast involved?
Example:
void bar(int& a);
int x;
int& y = x;
bar(y) // matching type
bar(x) // what happened here? was x cast to a reference?
A reference is formally a type; or at least you can read things like "if T is a reference type" in the C++ standard itself.
However, your question is perfectly legitimate in that references have very confusing semantics. They are not quite first-class types (for example, you can't have a reference-to-reference or a pointer-to-reference), and in my opinion that's because C++ managed to conflate two different kinds of types with how it defines and uses references.
What a reference really does is it gives an alternate name to an already-existing object (value). What does this mean? It means that it doesn't "qualify" the type of the value it refers to per se; it rather qualifies the name ("variable", "storage") itself that is used for referencing the value.
In C++, the semantics of a type and a value often depends on additional properties of the storage where the object/value is stored. This is not always explicit, and that's what confuses people.
I think because C++ heavily relies on exposing the concept of "storage" (rather than hiding it as an implementation detail), there really should be two type systems: one for pure values themselves, and one for storage, where the type system for storage should be a superset of the type system for values.
Another example where a very similar issue appears is CV-qualification. It's not an object/value itself that should be const or volatile. It's the storage containing that value that may or may not be mutable, and may or may not need to be protected from certain load/store optimizations. Again, this could be better expressed if there was a way to express these properties of types separately in the case of values and storage.
From what I can tell, references can be used wherever the original type can
That is simply not true.
Consider:
void foo(int x);
void bar(int& x);
foo(3);
bar(3); // whoops!
And how about this:
struct T
{
int& x;
};
It wouldn't make sense not to have a distinct type for references. This way, you get function overloading powers and every other benefit that the type system gives you.
You would otherwise need to invent some other mechanism to denote a thing as being a reference rather than a non-reference; surely the type system is the perfect mechanism to denote that?
int and int& are two distinct types.
” From what I can tell, references can be used wherever the original type can
No. A reference refers. You can think of it as a pointer in disguise.
” Are references separate types in C++?
Yes.
” If not, why are they written in the type?
That's just the syntax for specifying a reference type, using & as a type builder symbol. As another example, * is a type builder for pointers. Except for a limitation of type inference we could now replace that (1)impractical syntax with template syntax.
1) Both the creators of C and the creator of C++ have on several occasions described the original C declaration syntax as a “failed experiment”.
Unlike a pointer, a reference cannot be reseated; the address it is referencing cannot be changed. By like a pointer, the reference is useful when avoiding copying semantics, thus needing to create an alias to something that already exists... i.e., knowing it is a reference and not an object means the compiler knows not to copy the object at assignment or when passing through functions.
EDIT: regarding the updated questions, "if references are a different type, why can they be substituted for the original type in so many situations, without explicit casting? Is there implicit casting involved?" ... not casting, it is a reference so it simply gets "dereferenced" by "pointing" to the original object; it may help to just think of it as just a substitution name, or an alias, etc.

Can you access anonymous objects/types in C++?

I'm currently learning about references in C++. Here's something I've been wondering about:
int x = 5;
const int &ref = 3 * x + 1;
My understanding of this is that an anonymous variable is created for this expression 3 * x + 1 to be stored in it. After that, we tie our reference ref to that anonymous variable. That way we can access it although we can't change the value because its type is const.
Question: Is there a way we can access this anonymous variable/object apart from using the reference ref? In general, does C++ allow access to these anonymous objects?
This is called a temporary object (it is not a variable). And it doesn't store the expression, but the result of the expression.
Normally such objects are destroyed at the end of the full expression in which they are created. However if a reference is bound to them immediately, then these objects will live as long as that reference (with some exceptions not applying here).
So yes, you can use ref here exactly in the same way as if you had written
const int ref = 3 * x + 1;
instead. (With some minor exceptions like decltype(ref) being different.)
There is no other way to access such objects other than binding a reference to them. But that isn't really a restriction. You can do (almost) everything you can do with the name of a variable also with a reference to a variable/object.
Let's start first with the terminology: what you called "anonymous" is actually called "temporary" in the C++ language. Temporary variables/objects/instances are those that are implicitly declared as part of a C++ expression, but are not explicitly assigned to a variable.
For example, in your code snippet "3 * x" would be a temporary value. Temporary expressions are managed by the compiler, so there is no no way for you to access them from regular C++ code. If you need to do so, just declare a variable with the temporary result that you need and use it.
Being said that, I believe that you may be missing how references "&" work in C++. When you declare a type with the reference sign at the end (such as your "const int & ref") you are telling the compiler that "ref" is an alias of what is being assigned to ref, in this case, an alias of "3 * x + 1". Your code snippet works because you are declaring that reference as "const", thus the compiler can treat the "const int&" as a regular "const int" and use the computed value wherever it is needed.
However, if you remove the "const" you will see that you code cannot be compiled. That happens because without the "const", you are declaring a regular reference, which by definition can be changed. However, since you are assigning to it the result of a temporary expression (which of course cannot be changed because it is temporary) and it has no predetermined storage, the compiler is finding a wrong usage of a reference.

What is a "variable" in C++? [duplicate]

The standard says
A variable is introduced by the declaration of an object. The variable's name denotes the object.
But what does this definition actually mean?
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects? Or is a variable the name itself?
Or is a variable a named object in the sense that every variable is also an object?
Or is a variable just a "proxy" with a name that "delegates" all operations to the real object?
To confuse things further, many C++ books seem to treat variables and objects as synonyms.
What is your take on this?
About entities, quoting from the C++0x draft:
An entity is a value, object, reference, function [...]
Every name that denotes an entity is introduced by a declaration.
A variable is introduced by the declaration of an object
From these statements I draw the conclusion that a variable is a name and thus cannot be an object. This is really confusing the hell out of me :)
Variables are named objects. The following create objects that are not variables
new int // create one int object
std::string() // create one string object
The following creates one array variable with name "foo" and 5 unnamed (sub-) objects of type "int"
int foo[5];
The following is not a variable in C++03, but has become a variable in C++0x (declared references are variables in C++0x, for details see the link)
extern int &r;
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects?
Variables are objects (or references respectively). The entity list (3/3 in C++03) of C++ contains multiple such is-a relationships. For instance, a sub-object is-a object and an array element is-a object and a class-member is-a object or function or type or template or enumerator.
The entity list of C++0x looks a bit cleaner to me, and it doesn't contain "variables", "instance of a function" (what that kind of entity even is has never been apparent to me), "sub-object" and "array element" anymore. Instead it added "template specialization" which either are functions, classes or templates (partial specializations).
The C++ object model at 1.8 says
An object can have a name (clause 3).
So if you like, you can formulate the statement as "The object's name denotes the object.".
Variables are names that you give to objects, so yes, objects are, by and large, anonymous.
Here's the definition from the C++17 standard:
A variable is introduced by the declaration of a reference other
than a non-static data member or of an object. The variable’s name, if
any, denotes the reference or object.
My take on this, quite frankly, is that that's not really a definition. It tells us what introduces a variable, but it doesn't define what a variable is.
Consider, for example:
int foo = 42;
This is a declaration of an object, so it "introduces" a variable. But what is the variable? Is the object named foo a variable? I would have thought so, but the definition doesn't actually say that. Apparently the "variable" has a name (in this case "foo") and that name denotes the object. Since it has a name, presumably the name itself is not the variable. And it would have been easy enough to say that the variable is the object, rather than that the variable's name denotes the object, if that were the intent.
What is a "variable" in C++? I really don't know, and I don't believe it's possible to answer the question based on the wording in the standard. (And I'd like that to be corrected in a future edition.)
(The C standard deals with this by not defining "variable" and, for the most part, not using it except as an adjective or informally.)
A variable is simply an entity with a type and a name
As I have learned
What are variables
A variable is an identifier that is bind to a value stored in the system's memory(imperative languages) or an expression that can be evaluated(functional languages).
Why we need variables
provide names for storage chunks to store data temporarily during the lifespan of a computer program.
are also used in programming to transfer information from one part of the program to another part(Eg: parameters, global variables).
A variable is really a name given to an object in memory and hence an object is an anonymous type in that respect just at the point before compilation, when the compilation occurs, the variable is kept track of during the syntactical and parsing phase, then when the linker kicks in, that variable will have a memory address assigned to it, although at run-time, that memory address will be correctly off-setted somewhere to take into account of dynamic linking or static linking. Hence the variable can then be easily referenced aka the memory address that the variable is assigned to.
Really, in a nutshell, the variable is to help the programmer to work out the junction points of execution where that variable is referenced in terms of machine code.
What is your take on this?
Variable is a block of memory on stack or in code segment, or a value in a register (if the size of variable is small enough, although normally it is still value in a memory while registers hold temporary results), with name provided for programmer's convenience. Name of variable does not exist after compilation (we're not talking about macro tricks here). Any access to the variable is resolved into memory access, so technically variable is an address of corresponding data block, and that address isn't stored anywhere. Think about declaration of variables in assembly languages - variable "kinda" exists, but it is still merely an offset to the data block.
I think that this definition is quite clear.
The variable is introduced by declaration and denotes the object. Who introduces the variable? You do of course, and thus it is you who uses it.
A variable is really only a convenience for you the developer. It is a fundamental aspect of most programming languages not just C++. A variable mearly gives a symbolic name to a useable entity that occupies storage, such that it can be referenced and used at a future point in your source code.
For example if you declare a variable in a method as such:
int x = 5;
This will be reduced by the compiler to some offset from the stack pointer, say SP + 0x003.
At some point later you can say:
x = 52;
In this case the area of stack memory SP + 0x003 will contain the bytes that describe the number 52.
You declare the variable to be of a certain type so that the compiler can work out how much space the data occupies in memory.
Without variables, you would have to manage all of the arrangement of information yourself and you would probably be coding in assembly or lower.
Variable is a name for the object. You access the object through this named entity.

Are alias and reference the same thing in C++?

I'm not asking the difference between pointer and reference. Just a bit confused about the difference between reference and alias.
As far as I'm concerned, reference is a data type while alias is just a word describing the utility of this data type?
Thanks!
Aliasing refers to any way to refer to the same data through different names. References and pointers are two ways of achieving this behavior.
No, a reference is not a data-type, a reference references some other variable. Using a reference is the same as using the variable it references. It's very similar to a pointer (and it's not unlikely that the compiler treats references as pointers under the hood).
I've never heard of "alias" by itself in the context of C++, but there are type-aliases, created by e.g. typedef or using. There's also aliasing which is unrelated to both references and type-aliases.
Sorry, you said you were not asking the difference between a pointer and a reference.
To answer what you’re asking, the word reference means that a variable is pointing to a location in memory. Alias has a few different meanings, but the one I’ve seen most often in this context is that more than one variable are referencing the same location in memory, such as when you try to call memcpy(p, p, n);. One way to make this happen is with a C++ reference, which is a term of art for a language feature similar but not identical to pointers. Not every reference in C++ necessarily refers to something which ever has another name. You can also do aliasing with pointers, the address operator, a call by reference, or the compiler merging constants so that "Hello" and "Hello" in two places point to the same bytes in memory, or unions. Probably not exhaustive.
If people want to call a reference to something an “alias” even when there isn't any other variable referencing the same memory at the same time, I’m not strongly motivated to argue.
As several others have pointed out, C++14 uses the term “alias” to refer to template types declared with using. (http://en.cppreference.com/w/cpp/language/type_alias)
A type alias declaration introduces a name which can be used as a synonym for the type denoted by type-id. It does not introduce a new type and it cannot change the meaning of an existing type name. There is no difference between a type alias declaration and typedef declaration. This declaration may appear in block scope, class scope, or namespace scope.
From http://en.cppreference.com/w/cpp/language/type_alias

What exactly is a variable in C++?

The standard says
A variable is introduced by the declaration of an object. The variable's name denotes the object.
But what does this definition actually mean?
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects? Or is a variable the name itself?
Or is a variable a named object in the sense that every variable is also an object?
Or is a variable just a "proxy" with a name that "delegates" all operations to the real object?
To confuse things further, many C++ books seem to treat variables and objects as synonyms.
What is your take on this?
About entities, quoting from the C++0x draft:
An entity is a value, object, reference, function [...]
Every name that denotes an entity is introduced by a declaration.
A variable is introduced by the declaration of an object
From these statements I draw the conclusion that a variable is a name and thus cannot be an object. This is really confusing the hell out of me :)
Variables are named objects. The following create objects that are not variables
new int // create one int object
std::string() // create one string object
The following creates one array variable with name "foo" and 5 unnamed (sub-) objects of type "int"
int foo[5];
The following is not a variable in C++03, but has become a variable in C++0x (declared references are variables in C++0x, for details see the link)
extern int &r;
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects?
Variables are objects (or references respectively). The entity list (3/3 in C++03) of C++ contains multiple such is-a relationships. For instance, a sub-object is-a object and an array element is-a object and a class-member is-a object or function or type or template or enumerator.
The entity list of C++0x looks a bit cleaner to me, and it doesn't contain "variables", "instance of a function" (what that kind of entity even is has never been apparent to me), "sub-object" and "array element" anymore. Instead it added "template specialization" which either are functions, classes or templates (partial specializations).
The C++ object model at 1.8 says
An object can have a name (clause 3).
So if you like, you can formulate the statement as "The object's name denotes the object.".
Variables are names that you give to objects, so yes, objects are, by and large, anonymous.
Here's the definition from the C++17 standard:
A variable is introduced by the declaration of a reference other
than a non-static data member or of an object. The variable’s name, if
any, denotes the reference or object.
My take on this, quite frankly, is that that's not really a definition. It tells us what introduces a variable, but it doesn't define what a variable is.
Consider, for example:
int foo = 42;
This is a declaration of an object, so it "introduces" a variable. But what is the variable? Is the object named foo a variable? I would have thought so, but the definition doesn't actually say that. Apparently the "variable" has a name (in this case "foo") and that name denotes the object. Since it has a name, presumably the name itself is not the variable. And it would have been easy enough to say that the variable is the object, rather than that the variable's name denotes the object, if that were the intent.
What is a "variable" in C++? I really don't know, and I don't believe it's possible to answer the question based on the wording in the standard. (And I'd like that to be corrected in a future edition.)
(The C standard deals with this by not defining "variable" and, for the most part, not using it except as an adjective or informally.)
A variable is simply an entity with a type and a name
As I have learned
What are variables
A variable is an identifier that is bind to a value stored in the system's memory(imperative languages) or an expression that can be evaluated(functional languages).
Why we need variables
provide names for storage chunks to store data temporarily during the lifespan of a computer program.
are also used in programming to transfer information from one part of the program to another part(Eg: parameters, global variables).
A variable is really a name given to an object in memory and hence an object is an anonymous type in that respect just at the point before compilation, when the compilation occurs, the variable is kept track of during the syntactical and parsing phase, then when the linker kicks in, that variable will have a memory address assigned to it, although at run-time, that memory address will be correctly off-setted somewhere to take into account of dynamic linking or static linking. Hence the variable can then be easily referenced aka the memory address that the variable is assigned to.
Really, in a nutshell, the variable is to help the programmer to work out the junction points of execution where that variable is referenced in terms of machine code.
What is your take on this?
Variable is a block of memory on stack or in code segment, or a value in a register (if the size of variable is small enough, although normally it is still value in a memory while registers hold temporary results), with name provided for programmer's convenience. Name of variable does not exist after compilation (we're not talking about macro tricks here). Any access to the variable is resolved into memory access, so technically variable is an address of corresponding data block, and that address isn't stored anywhere. Think about declaration of variables in assembly languages - variable "kinda" exists, but it is still merely an offset to the data block.
I think that this definition is quite clear.
The variable is introduced by declaration and denotes the object. Who introduces the variable? You do of course, and thus it is you who uses it.
A variable is really only a convenience for you the developer. It is a fundamental aspect of most programming languages not just C++. A variable mearly gives a symbolic name to a useable entity that occupies storage, such that it can be referenced and used at a future point in your source code.
For example if you declare a variable in a method as such:
int x = 5;
This will be reduced by the compiler to some offset from the stack pointer, say SP + 0x003.
At some point later you can say:
x = 52;
In this case the area of stack memory SP + 0x003 will contain the bytes that describe the number 52.
You declare the variable to be of a certain type so that the compiler can work out how much space the data occupies in memory.
Without variables, you would have to manage all of the arrangement of information yourself and you would probably be coding in assembly or lower.
Variable is a name for the object. You access the object through this named entity.