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?
CodePudding user response:
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.
CodePudding user response:
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.