Any type can be referenced in a declaration.
For example
#include <iostream>
int main()
{
const char *s = "Hello";
const char * &reference_to_s = s;
std::cout << reference_to_s << '\n';
}
The same program can be rewritten also the following way
#include <iostream>
using T = const char *;
int main()
{
T s = "Hello";
T & reference_to_s = s;
std::cout << reference_to_s << '\n';
}
Thus the parameters of the function swap
void swap(char * &str1, char * &str2);
are references to pointers to non-constant strings/arrays.
In the first call there is an attempt to swap values of two pointers that are passed by reference.
However this call
swap(str1, str2);
is incorrect because the arguments have the type const char *
while the parameters declared without the qualifier const
.
Using the alias declaration shown above your program can be written like
#include <iostream>
using T = const char *;
void swap( T &s1, T &s2 )
{
T temp = s1;
s1 = s2;
s2 = temp;
}
int main()
{
T str1 = "GEEKS";
T str2 = "FOR GEEKS";
std::cout << "str1 is " << str1 << '\n';
std::cout << "str2 is " << str2 << '\n';
std::cout << '\n';
swap( str1, str2 );
std::cout << "str1 is " << str1 << '\n';
std::cout << "str2 is " << str2 << '\n';
std::cout << '\n';
}
Its output is
str1 is GEEKS
str2 is FOR GEEKS
str1 is FOR GEEKS
str2 is GEEKS
The next step to make references more clear is substitute the alias declaration and the non-template function swap
for a template function swap
.
#include <iostream>
template <typename T>
void swap( T &s1, T &s2 )
{
T temp = s1;
s1 = s2;
s2 = temp;
}
int main()
{
const char *str1 = "GEEKS";
const char *str2 = "FOR GEEKS";
std::cout << "str1 is " << str1 << '\n';
std::cout << "str2 is " << str2 << '\n';
std::cout << '\n';
swap( str1, str2 );
std::cout << "str1 is " << str1 << '\n';
std::cout << "str2 is " << str2 << '\n';
std::cout << '\n';
char c1 = 'A';
char c2 = 'Z';
std::cout << "c1 is " << c1 << '\n';
std::cout << "x2 is " << c2 << '\n';
std::cout << '\n';
swap( c1, c2 );
std::cout << "c1 is " << c1 << '\n';
std::cout << "x2 is " << c2 << '\n';
std::cout << '\n';
}
The program output is
str1 is GEEKS
str2 is FOR GEEKS
str1 is FOR GEEKS
str2 is GEEKS
c1 is A
x2 is Z
c1 is Z
x2 is A
So in the first call of swap
the referenced type is const char *
. In the second call of swap
the referenced type is char
.