Srinath Thumati Srinath Thumati - 1 month ago 15
C++ Question

Swapping two strings in C++

What does the arguments (char * &str1, char * &str2) specify in the swap function? What if they are replaced by (char &str1, char &str2) and char *temp=str1 with char &temp=str1 inside the swap function?

#include<iostream>
using namespace std;

void swap(char * &str1, char * &str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}

int main()
{
char *str1 = "GEEKS";
char *str2 = "FOR GEEKS";
swap(str1, str2);
cout<<"str1 is "<<str1<<endl;
cout<<"str2 is "<<str2<<endl;
return 0;
}

Answer

What does the arguments (char * &str1, char * &str2) specify in the swap function?

they specify that parameters are of type reference to pointer to char. This means that function might change the value of the variable that was provided as argument to this function.

What if they are replaced by (char &str1, char &str2) and char *temp=str1 with char &temp=str1 inside the swap function?

then you will get compiler error, because you will still call it like: swap(str1, str2);, you would have to change the call to swap(*str1, *str2); and then you will swap first letter of both strings.

[edit]

Your code includes also another subtle error, you use using namespace std; which causes std::swap to be called when you change your swap function signature to void swap(char &str1, char &).

You should also see warnigs like:

main.cpp:17:14: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic] char *str1 = "GEEKS";

this is because string literals are const pointers, otherwise you introduce UB in your code. You should change to const char *str1

Comments