why do we use Constant Reference Parameters in this code
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Converts a hex number as a string to decimal
int hex2Dec(const string& hex); // here why we use reference and const it seems we do not change hex in the function body
// Converts a hex character to a decimal value
int hexCharToDecimal(char ch);
int main()
{
// Prompt the user to enter a hex number as a string
cout << "Enter a hex number: ";
string hex;
cin >> hex;
cout << "The decimal value for hex number " << hex
<< " is " << hex2Dec(hex) << endl;
return 0;
}
int hex2Dec(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++)
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
return decimalValue;
}
int hexCharToDecimal(char ch)
{
ch = toupper(ch); // Change it to uppercase
if (ch >= 'A' && ch <= 'F')
return 10 + ch - 'A';
else // ch is '0', '1', ..., or '9'
return ch - '0';
}
what is the use of calling by reference in this problem ?
in this segment of code
int hex2Dec(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++)
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
return decimalValue;
}
we do not change the hex.
what is the purpose of const reference in this example and in genral?