This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 2 years ago.
I understand the basic difference between the passing by value and passing by reference. Passing by value means that you pass values as function arguments and passing by reference means that you just simply pass the variable.
What I don't get is how exactly works. Here is my example.
#include <iostream>
// Initializing Functions
void swap(int &first, int &second);
void write_and_prompt();
int main()
{
int num1 {30};
int num2 {185};
std::cout << "The original value of num1 is: " << num1 << '\n';
std::cout << "The original value of num2 is: " << num2 << '\n';
std::cout << "\nSwapping values..." << '\n';
std::cout << "Values have been swapped." << '\n';
// Function for swapping values.
swap(num1, num2);
std::cout << "\nThe value of num1 is: " << num1 << '\n';
std::cout << "The value of num2 is: " << num2 << '\n';
// Function that ends program after users input
write_and_prompt();
} // End of main
// Creating Fucntions
void swap(int &first, int &second)
{
int temp = first;
first = second;
second = temp;
}
void write_and_prompt()
{
std::cout << "\nPress enter to exit the program." << '\n';
std::cin.get();
}
So what I don't understand is when I call the function swap(num1, num2) I'm passing these two variables but in the syntax of the function I have &first, &second.
I thought that I was passing the address of num1 and num2 but then I thought that I would need pointers in the function to be able to work with them plus I would use the address-of operator in front of num1 and num2 instead.
Anyway what I trying to understand is why using the address-of operator(&) makes the function take the variables num1 and num2.
I thought that this operator just gives the address of the variable or maybe I didn't understand it correctly.
You are correct that the unary & operator gives the address of a variable. However, & in function arguments is not the address-of operator--it's marking that particular parameter as being pass-by-reference, which has different semantics than passing around pointers. If you want to pass in pointers, you'd use int *first, int *second, same as declaring a pointer-to-an-integer within a function body.
int & is a reference to int and is different from address-of operator. Your function parameters are references so you don't need to pass address or pointers.
Related
When using the address transfer of function, View address blocks of formal parameters and actual parameters, I find that the arguments and formal parameters of array share one address block, while the arguments and formal parameters of variables use two address block. What is the reason?
The code is as follows:
#include<iostream>
using namespace std;
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
int main() {
int i = 1, arr[2] = {1,2};
cout << &i << endl;
test(&i, arr);
cout << arr << endl;
system("pause");
return 0;
}
And this is the output:
0000008986B6FC54
0000008986B6FC30
0000008986B6FC78 //Arrays use the same space
0000008986B6FC78
You are passing pointers to the functions. The value of the pointers are not modified, ie in the function they point to the same objects as they do in main.
However, you are not printing what you think you print:
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
The pointer i gets the parameter &i (the i from main). Hence printing i in main will yield the same value as printing i in test. However, you are printing the adress of i in the function not the value of it. If you change your code to:
void test(int *i,int * arr) {
cout << &i << endl;
cout << i << endl;
cout << arr << endl;
}
You will notice the difference. I suggest you to rename at least one of the is in your code, because using same name for different entities can and does cause confusion. The i in test holds the value of the address of the i in main. That does not mean that they are the same, but rather i in test has the same value as &i in main.
In short: &i == &i but you expect &(&i) to be the same as &i.
There is no difference between passing a pointer to the int or passing a pointer to the first element of the array. From the point of view of the function they are both just pointers to int.
Note that test prints the value of arr but the location of i.
In test, &i is the location of its argument i.
That argument's value is the location of the i in main.
You will see this if you print i instead of &i.
arr, on the other hand, is implicitly converted into a pointer to its first element, and you are both passing &arr[0] to test to print, and printing &arr[0] in main.
Here is the same thing with explicit conversions and without using a function:
int main() {
int i = 1, arr[2] = {1,2};
cout << &i << endl;
// Create the "argument"...
int *p = &i;
// These two lines are 'test'...
cout << &p << endl;
cout << &arr[0] << endl;
// and this is after the function call.
cout << &arr[0] << endl;
}
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
C++ Difference Between Const Reference to Non Const Object and Non Const Reference to Non Const Object
(6 answers)
Closed 3 years ago.
I'm new to C++ and I'm confused about the differences between a normal ordinary reference to a read-only reference. The following two points are from http://www.lmpt.univ-tours.fr/~volkov/C++.pdf.
A reference must be initialized when it is declared, and cannot be modified subsequently. In other words, you cannot use the reference to address a different variable at a later stage.
A reference that addresses a constant object must be a constant itself, that is, it must be defined using the const keyword to avoid modifying the object by reference.
I was wondering, how to understand it? A normal reference is different to a read-only (or constant) reference; because a read-only reference can point to a constant object, in contrast to a normal reference. But the above two points are really confusing...Especially, "a reference must be initialized when it is declared, and cannot be modified later".
EDIT: sorry that I did not make it clear earlier. What I intended to ask is that, what is the difference between a normal reference and a read-only reference? It has nothing to do with pointers for now.
EDIT again: I finally figure it out. For completeness, the following is the code and comments.
#include <iostream>
#include <string>
using namespace std;
int main(){
string line(50, '-');
/* a constant reference, non-constant object */
int i=42; // a non-constant object
const int& r1 =i; // a constant reference r1, which reference the earlier defined variable i
//r1 = 6*9; // Error: tried to change the reference r1
i = 50;
cout << "r1: " << r1 << endl;
cout << "i: " << i << endl;
/* a constant reference, constant object */
const int j = 40;
// int& r2 = j; // Error, because j is a constant, it requires a constant reference
const int& r2 = j;
// j = 45; // Error, because j is a constant
//r2 = 20; // Error, because r2 is a constant reference
/* non constant reference, non constant object */
int k = 30;
int& r3 = k;
r3 = 10; // update
cout << "r3: " << r3 << endl;
cout << "k: " << k << endl;
cout << line << endl;
k = 40; // update
cout << "r3: " << r3 << endl;
cout << "k: " << k << endl;
return 0;
}
EDIT again again: Now, I'm confused with "a reference must be initialized when it is defined, and cannot be modified later".
/* how to understand a reference can not be used to address a different variable */
int a = 1;
int b = 2;
int& r = a; // r is a reference, which references variable (object) a
r = b; // expect an error, but did not get an error
cout<< "a: " << a << endl; //2
cout<< "b: " << a << endl; //2
cout<< "r: " << a << endl; //2
I wanted to create a function that retrieves all the information from previous functions within the same Class, and prints the values that were returned in the format of a bunch of cout statements, there is nothing for me to return in this PrintStatement() function, so I would create a void function, correct? My issue is in the int main(), I cannot cout a void function.
this is my account header file, and the function piece from my account.cpp file.
class Account {
public:
//Object constructor
Account(char firstName[], char lastName[], char sinNumber[], double balance, int accountType, int transactions);
//Object operations
double DepositAmt(double amount);
double WithdrawAmt(double amount);
void PrintStatement();
double getFinalBalance(double fbal);
string getAccountType();
double getTransactions (double Deposit, double Withdraw);
private:
//Object properties
char firstName[255];
char lastName[255];
char sinNumber[255];
double balance;
int accountType;
int transactions;
};
void Account::PrintStatement()
{
cout << "First Name: " << firstName << endl;
cout << "Last Name: " << lastName << endl;
cout << "SIN Number: " << sinNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Final Balance: " << balance << endl;
cout << "Transactions: " << transactions << endl;
};
the global variables have already been initialized.
What I've tried:
I originally tried to cout << account.PrintStatement() << endl; however I get an error C2679 (binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)
I thought maybe changing things to apply to a string function instead would work, but instead I get a bunch of int conversion errors etc.
I'm unsure of what to do.
I am required to put these in a function just to be clear.
I tried using this question https://stackoverflow.com/questions/12766858/how-to-call-void-function-from-main to help me, it made sense that the poster was using a reference, but I do not have that. Is there another way?
I originally tried to cout << account.PrintStatement() << endl;
Well, the expression account.PrintStatement() is abject nothingness because the function has a void return type. As you've indicated, the function returns nothing, so there is nothing to stream to cout.
The function itself has already streamed a bunch of stuff to cout, fulfilling all your couty needs. So, simply invoke it:
account.PrintStatement();
That's it!
Just call the method on your instance of the class. It doesn't need to return anything; it will do the counts you want and then return to main.
When we use cout<<something_here, the compiler will interpret it as "print the value of something_here". Now, something_here can be a lot of things. When it is a function, cout will print the value returned by the function. In your case, the return type is void i.e. nothing. So, there is nothing to print.
To fix your issue, you can directly call account.PrintStatement(); since you have already printed what you wanted to print inside this function.
Please look at the code snippet below - I have declared 3 functions (i.e. 1 passing an int and the others passing reference to an int). After executing the program I found that the value of "count" variable after calling function (tripleByReference) has not been changed to reflect its triple (count is still equal to 5). However calling function (tripleByReferenceVoid) modifies the variable but this is due to the fact that changes occurred directly to the variable (count).
I understand that with pass by reference, the caller gives the called function the ability to access the caller's data directly and modify it but that could not be achieved by passing the variable to function (tripleByReference) - Please help me to understand this.
#include <iostream>
using namespace std;
/* function Prototypes */
int tripleByValue(int);
int tripleByReference(int &);
void tripleByReferenceVoid(int &);
int main(void)
{
int count = 5;
//call by value
cout << "Value of count before passing by value is: " << count << endl;
cout << "Passing " << count << " by value, output is: "
<< tripleByValue(count) << endl;
cout << "Value of count after passing by value is: " << count << endl;
//call by reference - using int tripleByReference
cout << "\n\nValue of count before passing by reference is: " << count << endl;
cout << "Passing " << count << " by reference, output is: "
<< tripleByReference(count) << endl;
cout << "Value of count after passing by reference is: " << count << endl;
//call by reference - using void tripleByReference
tripleByReferenceVoid(count);
cout << "\n\nValue of count after passing by reference is: " << count << endl;
cout << endl;
system("PAUSE");
return 0;
}//end main
int tripleByValue (int count) {
int result = count * count * count;
return result;
}//end tirpleByValue function
int tripleByReference(int &count) {
int result = count * count * count;
return result; //perform calcs
}//end tripleByReference function
void tripleByReferenceVoid(int &count) {
count *= count * count;
}//end tripleByReference function
Thank you.
tripleByReference doesn't change the value of count because you never assign to it. You are returning the value instead.
tripleByReferenceVoid is different. You are assigning to it (count *= ...) and that is why these changes are reflected.
In your function tripleByReference you are not even attempting to modify the value of count, while in your function tripleByReferenceVoid you are explicitly modifying count. Hence the obvious and expected effect: the latter function modifies count, the former doesn't. I.e. these functions do exactly what and only what you explicitly and consciously asked them to do.
Questions like this one is difficult to answer because it is virtually impossible to understand what made you to ask it. You seem to be puzzled by the fact that the behavior of these two functions is different. But why does it puzzle you, when you yourself explicitly wrote them to be different in that specific regard?
The following code has overloaded function CandyBarFunc. First prototype defines the function so that it modifies the value of a structure. Second prototype defines the function so that it just displays the content of a passed structure. The problem is that when I run the console program nothing appears on the screen except the Press Any Key...
I tried to debug it and found out that first prototype works properly(I added the display functionality from the second prototype to the first one) becuase it modified and displayed the contents of the structure. So therefore it seems that overloading didn't work because the second function prototype doesn't get called during execution because nothing is displayed on the console screen. I'm not sure if the signaure is bad because the compiler does't complain about the ambigious function call. Did I miss something obvious in the code?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
char name[40];
double weight;
int calories;
};
void CandyBarFunc(CandyBar & astruct, const char * aname = "Millennium Munch", double aweight = 2.85, int acalories = 350);
void CandyBarFunc(const CandyBar & astruct);
int main(void)
{
CandyBar MyCandyBar =
{
"Hi",
1.5,
456
};
cout << "1" << endl; 'little debug'
CandyBarFunc(MyCandyBar); 'suppose to display the contents of MyCandyBar'
CandyBarFunc(MyCandyBar, "Hello World Candy Bar", 1.25, 200); 'suppose to modify MyCandyBar
CandyBarFunc(MyCandyBar); 'suppose to display the contents of MyCandyBar again'
cout << "2"; 'little debug'
return 0;
}
void CandyBarFunc(CandyBar & astruct, const char * aname, double aweight, int acalories)
{
strncpy_s(astruct.name,aname,40);
astruct.weight = aweight;
astruct.calories = acalories;
cout << "Name: " << astruct.name << endl; 'not suppose to be here, just for debug'
cout << "Weight: " << astruct.weight << endl; 'not suppose to be here, just for _ debug'
cout << "Calories: " << astruct.calories; 'not suppose to be here, just for debug'
}
void CandyBarFunc(const CandyBar & astruct)
{
cout << "Name: " << astruct.name << endl;
cout << "Weight: " << astruct.weight << endl;
cout << "Calories: " << astruct.calories;
}
Exercise:
The CandyBar structure contains three members. The first member holds the brand
name of a candy bar. The second member holds the weight (which may have a fractional
part) of the candy bar, and the third member holds the number of calories (an integer
value) in the candy bar. Write a program that uses a function that takes as arguments a
reference to CandyBar, a pointer-to-char, a double, and an int and uses the last three
values to set the corresponding members of the structure. The last three arguments
should have default values of “Millennium Munch,” 2.85, and 350. Also, the program
should use a function that takes a reference to a CandyBar as an argument and displays
the contents of the structure. Use const where appropriate.
Since MyCandyBar isn't const, the compiler choses the first (reference to non-const) overload.
But seriously, if you want one function to set properties and another function to print them out, please don't abuse overloading by giving them the same name. Just name them differently, no more problems.
Also, in C++ we prefer std::string to fixed-size character arrays and character pointers.
Since MyCandyBar is not const, it will always try to use the function which accepts the non const CandyBar. You can force it to call the other function by casting it to const:
CandyBarFunc((const CandyBar &)MyCandyBar);