c++ function: pass non const argument to const reference parameter - c++

suppose I have a function which accept const reference argument pass,
int func(const int &i)
{
/* */
}
int main()
{
int j = 1;
func(j); // pass non const argument to const reference
j=2; // reassign j
}
this code works fine.according to C++ primer, what this argument passing to this function is like follows,
int j=1;
const int &i = j;
in which i is a synonym(alias) of j,
my question is: if i is a synonym of j, and i is defined as const, is the code:
const int &i = j
redelcare a non const variable to const variable? why this expression is legal in c++?

The reference is const, not the object. It doesn't change the fact that the object is mutable, but you have one name for the object (j) through which you can modify it, and another name (i) through which you can't.
In the case of the const reference parameter, this means that main can modify the object (since it uses its name for it, j), whereas func can't modify the object so long as it only uses its name for it, i. func could in principle modify the object by creating yet another reference or pointer to it with a const_cast, but don't.

const int &i = j;
This declares a reference to a constant integer.
Using this reference, you won't be able to change the value of the integer that it references.
You can still change the value by using the original variable name j, just not using the constant reference i.

Related

Can I initialize a constant integer with a L-value?

I've got a question in my assignment that asks me to evaluate whether the following function call is correct. I'm not sure if a const int can be initialized with a variable of type const int&. I know that a const int can be initialized with another int, for example
int i=3; const int j=i
works perfectly fine, but I'm not sure if the following code is semantically correct (the line const int j=bar(++i);)
int foo (int& i) {return i+=2;}
const int& bar(int &i){ return i+=2;}
int main(){
int i=5;
const int j=bar(++i);
}
Yes it can. You can initialize an object with any value category.
When constructing the type, it will simply call its constructor with the correct overload, such as type(type&& other) or type(type const&).
For trivial types, it's always a copy. So as long as the types are compatible, no matter their value category, it will work.
Initializing a reference is different. You must have an expression with a compatible value category. For example, creating a mutable reference from your function won't work:
int& j = bar(++i); // won't compile, int& cannot be bound to int const&
This is because bar returns a reference to const, thus cannot be bound to a reference to mutable.
As a side note, even though it's an int constant, it is not a compile time constant anymore. Thus you won't be able to use it as an array size or template parameter.
To fix that you'd have to use constexpr, which will guarantee that the value of your variable is available at compile time.
int a = 9;
constexpr int b = a; // Won't work, `a` is a runtime value, `b` is compile time
constexpr int a = 1;
constexpr int b = a + 1; // Works! Both compile time values
A reference is basically just an alias to the object it is bound to (with possible indication of immutability by const). Since bar(++i) returns a reference bound to i, it is the same as if you initialized j by i after bar(++i) call:
bar(++i);
const int j = i;
Const reference just says that you cannot modify the bound object through that reference. But there is nothing in your code that would try doing this.

Where and why do we use a reference to const? [duplicate]

void DoWork(int n);
void DoWork(const int &n);
What's the difference?
The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.
Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.
There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.
E.g.
int a;
void DoWork(const int &n)
{
a = n * 2; // If n was a reference to a, n will have been doubled
f(); // Might change the value of whatever n refers to
}
int main()
{
DoWork(a);
}
Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.
e.g.
void DoWork(const int &n)
{
const_cast<int&>(n) = 22;
}
This would cause undefined behaviour if the object passed in was actually const.
When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.
When the parameter is passed by value an extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.
The difference is more prominent when you are passing a big struct/class:
struct MyData {
int a,b,c,d,e,f,g,h;
long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);
When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If you are using const reference, you pass it by reference and the original data is not copied.
In both cases, the original data cannot be modified from inside the function.
EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.
There are three methods you can pass values in the function
Pass by value
void f(int n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.
Pass by reference
void f(int& n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference
Constant reference
void f(const int& n){
n = n + 10; // Error: assignment of read-only reference ‘n’
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.
With
void DoWork(int n);
n is a copy of the value of the actual parameter, and it is legal to change the value of n within the function. With
void DoWork(const int &n);
n is a reference to the actual parameter, and it is not legal to change its value.
Since none of you mentioned nothing about the const keyword...
The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)
In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.
The first method passes n by value, i.e. a copy of n is sent to the function. The second one passes n by reference which basically means that a pointer to the n with which the function is called is sent to the function.
For integral types like int it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.
Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.
$8.3.2/1- "Cv-qualified references are ill-formed except when the
cv-qualifiers are introduced through the use of a typedef (7.1.3) or
of a template type argument (14.3), in which case the cv-qualifiers
are ignored."
Here are the differences
$13.1 - "Only the const and volatile type-specifiers at the outermost
level of the parameter type specification are ignored in this fashion;
const and volatile type-specifiers buried within a parameter type
specification are significant and can be used to distinguish
overloaded function declarations.112). In particular, for any type T,
“pointer to T,” “pointer to const T,” and “pointer to volatile T” are
considered distinct parameter types, as are “reference to T,”
“reference to const T,” and “reference to volatile T.”
void f(int &n){
cout << 1;
n++;
}
void f(int const &n){
cout << 2;
//n++; // Error!, Non modifiable lvalue
}
int main(){
int x = 2;
f(x); // Calls overload 1, after the call x is 3
f(2); // Calls overload 2
f(2.2); // Calls overload 2, a temporary of double is created $8.5/3
}
Also, you can use the const int& x to initialize it with r-value and this will cause that you can't change x or bind it with another values.
const int& x = 5; // x is a constant reference to r-value 5
x = 7; // expression is not a modifable value

What does "ampersand operator" mean between a class and a variable?

I saw the following code in plumed and am quite confused:
void ActionAtomistic::makeWhole() {
for(unsigned j=0; j<positions.size()-1; ++j) {
const Vector & first (positions[j]);
Vector & second (positions[j+1]);
second=first+pbcDistance(first,second);
}
}
Could anyone tell me what "&" is used for here? I googled "c++ ampersand between class and variable" but did not find the answer.
Updated: I know what reference is but thought there should not be any space between Vector and "&". Thank you guys for clarifying that.
This means that first is a reference (in this case, a const reference) to an object of type Vector, rather than an object of type Vector.
Read more about references here.
That is known as a reference. I usually write references like Type& name to make it clear that the reference is part of the type.
References are like pointers that are easier to use but come with some restrictions. Here's an example of when you could use a reference:
void add1ToThisNumber(int& num) {
num += 1;
}
// elsewhere...
int myNumber = 3;
add1ToThisNumber(myNumber);
cout << myNumber; // prints 4
A reference (in this case) is basically an alias to another variable. While the following doesn't apply in the first case (as your reference is const), references can be used to modify the objects they are referring to. As an example:
int c = 5;
int& d = c;
d = 12; // c is set to 12
In your particular case, the reference is an immutable alias, so positions[j] cannot be modified through first.
In the second case, doing second = variable will evaluate to positions[j + 1] = variable.
& has different meanings based on context.
Declare a type.
int var;
int& ref1 = var; // Declares a reference to a variable
int const& ref2 = var; // Declares a const reference to a variable
int& foo(); // Declares foo() whose return type is reference to an int
void bar(int&); // Declares bar whose argument type is reference to an int
struct Foo
{
int& bar; // Declares bar to be member variable of the
// class. The type is reference to an int
};
Take address of a variable (any lvalue really)
int var;
int* ptr = &var; // Initializes ptr with the address of var
int arr[4];
int* ptr2 = &(arr[3]); // Initializes ptr2 with the address of the
// last element of arr
Perform bitwise AND operation.
int i = <some value>;
int j = <some value>;
int k = (i & j); // Initializes k with the result of computing
// the bitwise AND of i and j
What you have in your code is the first use.
const Vector & first (positions[j]);
That line declares first to be a const reference to position[j].

Passing const value by reference

Let's say I have this program:
const int width = 4;
void test(int&){}
int main() {
test(width);
}
This will fail to compile. I notice that constant values ( also enumeration constants ) with names ( such as width ) cannot be passed by reference. Why is that so?
Imagine this:
void test (int& j) { j++; }
If test does change the value of the thing referenced, clearly we can't call it with a const parameter. And if it doesn't, why does it take its parameter by non-const reference?
Passing by reference allows us to change the actual object.
If an object is defined as const, it cannot be changed. That is exactly what const means - it's constant.

What is the difference between a const reference and normal parameter?

void DoWork(int n);
void DoWork(const int &n);
What's the difference?
The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.
Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.
There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.
E.g.
int a;
void DoWork(const int &n)
{
a = n * 2; // If n was a reference to a, n will have been doubled
f(); // Might change the value of whatever n refers to
}
int main()
{
DoWork(a);
}
Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.
e.g.
void DoWork(const int &n)
{
const_cast<int&>(n) = 22;
}
This would cause undefined behaviour if the object passed in was actually const.
When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.
When the parameter is passed by value an extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.
The difference is more prominent when you are passing a big struct/class:
struct MyData {
int a,b,c,d,e,f,g,h;
long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);
When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If you are using const reference, you pass it by reference and the original data is not copied.
In both cases, the original data cannot be modified from inside the function.
EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.
There are three methods you can pass values in the function
Pass by value
void f(int n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.
Pass by reference
void f(int& n){
n = n + 10;
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference
Constant reference
void f(const int& n){
n = n + 10; // Error: assignment of read-only reference ‘n’
}
int main(){
int x = 3;
f(x);
cout << x << endl;
}
Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.
With
void DoWork(int n);
n is a copy of the value of the actual parameter, and it is legal to change the value of n within the function. With
void DoWork(const int &n);
n is a reference to the actual parameter, and it is not legal to change its value.
Since none of you mentioned nothing about the const keyword...
The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)
In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.
The first method passes n by value, i.e. a copy of n is sent to the function. The second one passes n by reference which basically means that a pointer to the n with which the function is called is sent to the function.
For integral types like int it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.
Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.
$8.3.2/1- "Cv-qualified references are ill-formed except when the
cv-qualifiers are introduced through the use of a typedef (7.1.3) or
of a template type argument (14.3), in which case the cv-qualifiers
are ignored."
Here are the differences
$13.1 - "Only the const and volatile type-specifiers at the outermost
level of the parameter type specification are ignored in this fashion;
const and volatile type-specifiers buried within a parameter type
specification are significant and can be used to distinguish
overloaded function declarations.112). In particular, for any type T,
“pointer to T,” “pointer to const T,” and “pointer to volatile T” are
considered distinct parameter types, as are “reference to T,”
“reference to const T,” and “reference to volatile T.”
void f(int &n){
cout << 1;
n++;
}
void f(int const &n){
cout << 2;
//n++; // Error!, Non modifiable lvalue
}
int main(){
int x = 2;
f(x); // Calls overload 1, after the call x is 3
f(2); // Calls overload 2
f(2.2); // Calls overload 2, a temporary of double is created $8.5/3
}
Also, you can use the const int& x to initialize it with r-value and this will cause that you can't change x or bind it with another values.
const int& x = 5; // x is a constant reference to r-value 5
x = 7; // expression is not a modifable value