I.e. are these legal statements:
int x = 1, y = z = 2;
int& a = x, b = c = y;
with the intended result that a is an alias for x, whileb and c are aliases for y?
I ask simply because I read here
Declaring a variable as a reference rather than a normal variable
simply entails appending an ampersand to the type name
which lead me to hesitate whether it was legal to create multiple reference variables by placing & before the variable name.
int x = 1, y = z = 2;--incorrect
int& a = x, b = c = y;--incorrect
The statements should be like this:
int x = 1, y =2,z = 2;
int&q=x,&b=y,&c=y;
All assignment and initialization statements in c++ should be of the following type:
lvalue=rvalue;
here lvalue must always be a variable to which a temporary value/another variable is assigned.
rvalue can be another variable or an expression that evaluates to a temporary variable like (4+5).
You need to append a & on the left of each reference (like you would need a * when you declare a pointer).
Related
For example:
int a = 0;
int& ref = a;
In this example it took a and add it another name - "ref", and they are the same place at the memory.
In this example:
int a = 0;
int& ref = a;
ref = 5;
it replaced the value of a (so that it replaced "also" the value of ref).
So now the assignment statement gets a new meaning?
When the referent is initialized, it binds itself to an object.
After, you are modifying the bound object, not the reference.
Think of the reference as a pointer you cannot modify once created (but that always points to a valid object, no null reference possible).
The = in the definition of an object is not an assignment; it's an initialization. And, yes, the meaning of an initialization is not the same as the meaning of an assignment.
int a = 0; // initialize a to 0
int& ref = a; // initialize ref to refer to a
ref = 5; // assign 5 to ref; ref is a reference, so this assigns 5 to a
Initialization refers to creating an object (in the example code, an int and an int&; the = sign in an initialization tells the compiler what to use as the initial value of that object.
Assignment refers to setting a new value to an already existing object. So int a = 0; is initialization; a = 3; is assignment.
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 8 years ago.
#import<iostream>
using namespace std;
int main()
{
//trying to test pointers & reference
int x = 5;
int y = 6;
int *p;
p = &y;
*p = 10;
int &r = x;
cout<<"X reference\n"<<&r<<"\n"<<"value:"<<r<<"\n";
r=y;
cout<<"Y reference\n"<<&r<<"\n"<<"value:"<<r<<"\n";
}
In this code, I have assigned &r to x at first and then I have assigned r to y.
What is the difference between assigning & r=x and r=y?
Kindly help me out.
int &r = x;
defines a reference to int variable.
References cannot change what they reference after they are defined, so the line
r=y;
is assigning x the value that is stored in y. It does not make r start referencing y. Any assignment to or from r will be treated as if it was from x.
Another way to think about references is as if they are a pointer variable which you cannot change what is pointed to after it is initialized and any occurrence of their usage has an implicit dereference (*) operator.
int& r = x declares a reference to x, think about it as an alias. So if you further down the line modify x, it will be reflected in r, for example,
x = 10;
cout << r; // r is "updated" here, as it is a reference to `x`
will print 10.
On the other hand, the declaration int r = x just copies the value of x into r, then r is completely independent of x. So modifying x will have absolutely no effect on r.
In a sense, reference are "kind-of" syntactic sugar for pointers, although not really the same, as you cannot have an uninitialized reference.
I am reading about references in C++. It says that int& a = 5 gives compile time error.
In Thinking in C++ - Bruce Eckel, author says that compiler must first allocate the storage for an int and produce the address to bind to the reference. The storage must be const because changing it would make no sense.
I am confused at this point. I am not able to understand the logic behind it. Why can't be change the content in the storage? I understand that it's invalid as per C++ rules, but why?
"The storage must be const because changing it would make no sense."
If you want a be a reference to a const value, you must declare it as const, because a is referencing to a temporary constant value, and changing it is not possible.
const int &a = 123;
a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
// We can not change 123 to 1000
// Infact, we can change a variable which its value is 123 to 1000
// Here `a` is not a normal variable, it's a reference to a const
// Generally, `int &a` can not bind to a temporary object
For non-const bindings:
int x = 1;
int &a = x;
a is a reference to a lvalue. Simple speaking, it's an alias name for another variable, so on the right hand you should give a variable. The reference a can not change and bind to another variable after it's first binding;
In C++11, you can reference to temporary objects/values by rvalue references:
int &&a = 123;
int& a = 5;
In order for the above code to work, int& needs to bind to a temporary object of type int created out of the expression 5. But binding int& to a temporay didn't appeal to Bjarne Stroustrup — and he gave an example, similar to the following, to illustrate his point:
void f(int &i) { ++i; }
float x = 10.0;
f(x);
std::cout << x <<< std::endl;
What will the std::cout print1? Looks like it will print 11.
It feels, ++i is changing the argument x, but it doesn't. This is one reason why the creator of C++ didn't permit temporaries to bind to non-const reference.
However, you can do this:
int const & i = 10;
int const & j = x; //x is float
And since C++11, you can do this:
int && i = 10;
int && i = x; //x is float
Hope that helps.
1. assuming int& can bind to the temporary created out of x.
What you can do is
int b=5;
int &a=b;
or
const int& a = 5;
Given the following c++ function:
int& ReturnAReference() {
/* Do something here */
}
Is there any difference between the two statements:
int normalVariable = ReturnAReference();
int& referenceVariable = ReturnAReferene();
Is one version preferred over the other?
Regarding this:
int normalVariable = ReturnAReference();
normalVariable is an integer, and is assigned the value of the int that ReturnAReference() references. As such incrementing, assigning, or doing anything else to normalVariable will not affect whatever ReturnAReference() has internally.
Regarding this:
int& referenceVariable = ReturnAReference();
referenceVariable is a reference to an integer that would otherwise be internal to ReturnAReference(). As such incrementing, assigning, or doing anything else to referenceVariable will affect whatever ReturnAReference() has internally.
What is preferred depends on what you're trying to accomplish, but in many cases the second approach (using referenceVariable) violates "encapsulation" ( http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) ), which is considered poor design.
EDIT: And I should add that if ReturnAReference() is returning a reference to a variable that is local in that function, that reference will be invalid as soon as ReturnAReference() returns.
After a reference has been initialized, e.g. via
int i = 42;
int& r1 = i;
int& r2 = ReturnAReference();
int& r3(i);
int& r4{i}; // C++11
int& r5 = {i}; // C++11
it becomes an alias, i.e. another name, of the object it has been initialized with. It is not another integer. Note that in the language of the C++ Standard, an object is simply a region of storage, not necessarily an instance of a class.
As a reference is an alias, if you operate with the reference, you'll operate on the original object (the one it has been initialized with):
int i = 42;
int& r = i;
// r is now an alias for i, both refer to the same object
r = 21; // a true assignment
std::cout << i; // will print 21
The statement
int normalVariable = ReturnAReference();
introduces a new object of type int and a name for that object: normalVariable. This object is initialized with the object returned by ReturnAReference(), which means that the value of the returned object is copied into the new object called normalVariable.
On the other hand, the statement
int& referenceVariable = ReturnAReferene();
only introduces a new name for the object returned by ReturnAReference().
If your function would return a non-reference int, like int ReturnAnInt();, the statement
int& r = ReturnAnInt();
would become illegal, as the object returned by this function is a temporary, which only lives until the end of this line (in this case). In the next line, the name r would refer to an object that does not exist any more, so it has been made illegal to bind non-const references to temporary objects.
Let's suppose you have the following definitions :
int test = 4;
int& ReturnAReference() {
return test;
}
1) Is there any difference between the two statements:
int normalVariable = ReturnAReference();
In this case, normalVariable will hold a copy of the return value (not a reference), because the assignment operator copies the value referred by the return value into normalVariable. This means that after
normalVariable = 1;
normalVariable will now be 1, but test will still be 4.
However, if you were to have written
int& referenceVariable = ReturnAReferene();
and do
normalVariable = 1;
normalVariable would now be 1 and test would also be 1, since normalVariable is only an alias for test.
Be careful though when you return a reference. For instance, if you were to do
int& ReturnAReference() {
int i = 0;
return i;
}
the reference returned from ReturnAReference() would not be valid anymore, since it is only valid inside the function and will be destroyed when it is exited.
2) Is one version preferred over the other?
In the case of ints or other primitive types, I would prefer the int return value over int&, simply because an int is small and won't be expensive to copy (it will nearly always fit in a register). Also, the int& return value entails safety issues if the reference refers to a local variable. For classes or structs, it always depends, but you have to be careful when returning local variables by reference or by pointer.
If you want to modify the variable returned by reference from the function, or to keep track of any changes to its value, use int&. It's up to you to make sure the variable you are referencing will exist for as long as you access it. If you just care about the value of the variable returned by reference at that point, use int.
FYI, std::vector's operator [] and at functions return by reference allowing syntax such as the following v.at(0) = 2.
I thought the following codes were correct but it is not working.
int x, *ra;
&ra = x;
and
int x, ra;
&ra = x;
Please help me if both of these code snippets are correct. If not, what errors do you see in them?
Your both expressions are incorrect, It should be:
int x, *ra;
ra = &x; // pointer variable assigning address of x
& is ampersand is an address of operator (in unary syntax), using & you can assign address of variable x into pointer variable ra.
Moreover, as your question title suggests: Assigning int value to an address.
ra is a pointer contains address of variable x so you can assign a new value to x via ra
*ra = 20;
Here * before pointer variable (in unary syntax) is deference operator gives value at the address.
Because you have also tagged question to c++ so I think you are confuse with reference variable declaration, that is:
int x = 10;
int &ra = x; // reference at time of declaration
Accordingly in case of the reference variable, if you want to assign a new value to x it is very simply in syntax as we do with value variable:
ra = 20;
(notice even ra is reference variable we assign to x without & or * still change reflects, this is the benefit of reference variable: simple to use capable as pointers!)
Remember reference binding given at the time of declaration and it can't change where pointer variable can point to the new variable later in the program.
In C we only have pointer and value variables, whereas in C++ we have a pointer, reference and value variables. In my linked answer I tried to explain differences between pointer and reference variable.
Both are incorrect.
When you declare a pointer, you assign it the address of a variable. You are attempting the other way round. The correct way would be:
int x,*ra;
ra = &x;
Both of those causes, in the way you have them in your question, undefined behavior.
For the first, you don't initialize the pointer, meaning it points to a random location (or NULL if the variable is global).
For the second, you try to change the address the variable is located at, which (if it even would compile) is not allowed.
Here's some annotated code:
int main () {
// declare an int variable
int x = 0;
// declare a pointer to an int variable
int *p;
// get the memory address of `x`
// using the address-of operator
&x;
// let `p` point to `x` by assigning the address of `x` to `p`
p = &x;
// assign `x` a value directly
x = 42;
// assign `x` a value indirectly via `p`
// using the dereference operator
*p = 0;
// get the value of `x` directly
x;
// get the value of `x` indirectly via `p`
// using the dereference operator
*p;
}
Note that dereferencing a pointer that doesn't point to a valid object of the specified type is not allowed.
So you normally shouldn't do things like the following (unless you really know what you are doing):
*(int*)(12345) = 42; // assign an integer value to an arbitrary memory address
Here is my 2 cent.
If you are going onto understanding pointer in C. First make the distinction between * the operator and * the type qualifier/specifier.
See that in C * is a syntaxique element that can plays both role but never at the same time. A type qualifier:
int a;
int * c = &a;
int * my_function_returning_pointer();
And for getting the proper int. As an operator. ( *c is an alias of a)
*c = 9;
I admit that is quite confusing and can trap a lot of beginner. Make sure that you recognize when * is used as an operator or when it is used as a type qualifier.
The same things apply to & although it is less often used as type qualifier.
int & f = returning_a_reference();
int my_function( int & refParam);
It is more often use for getting the address of an object. Thus it is used as an operator.
c = &f;
case 1:
int x,*ra;
&ra = x;
it is wrong in c, because in c we can point to a memory location by using a pointer ( i.e *ra in your case ). this can be done as fallows
int x, *ra; x ---------
ra=&x; ra --->1000 | value |
----------
NOTE : with out initializing a variable we can't use pointer to hold the address of that variable, so you better to first initialize variable, then set pointer to that memory location.
int x, *ra;
x=7;
ra=&x;
Fallowing may be helpful to you:
problems(mistake we do ) in handling pointers :
1.)
int a ,*p;
p=a; // assigning value instead of address. that leads to segmentation fault at run time.
2)
int a, *p;
&p=a; // look at here wrong assignment
3)
char *p="srinivas"
strcat(p, "helo" ) ; // we cant add a substring to the constant string.
4) int a=5, *p;
p=5; // the pointer here will points to location 5 in the memory, that may damage whole system, be care full in these type of assignments.