overloaded function with no contextual type information | cannot resolve overloaded function 'swap' based on conversion to type 'int'

Jonathan Dewein picture Jonathan Dewein · Feb 16, 2012 · Viewed 27k times · Source

I am trying to write my own bubble sort algorithm as an exercise. I do not understand the two error messages. Can anyone point out the problem with my code?

// Bubble sort algorithm
#include <iostream>
#include <iomanip>
using namespace std;

void bubbleSort(int array[], int arraySize); // bubbleSort prototype

int main(void)
{
        const int arraySize = 10;
        int array[arraySize] = {2,3,6,5,7,8,9,3,7,4};

        cout << "Unsorted: ";
        for(int i = 0; i < arraySize; ++i)
                cout << setw(5) << array[i];

        cout << "Sorted: " << bubbleSort(array, arraySize);
}

void bubbleSort(int array[], int arraySize)
{
        const int max = arraySize;
        int swap = 0;

        for(int i = 0; i < max; ++i)
        {
                if(array[i] > array[i + 1])
                {
                        swap = array[i + 1];
                        array[i + 1] = array[i];
                        array[i] = swap;
                }
                else
                        break;
        }
}

Answer

Alexander Kondratskiy picture Alexander Kondratskiy · Feb 16, 2012

I see that you are using

using namespace std;

So when you type

array[i] = swap;

The compiler cannot disambiguate whether you are referring to the std::swap function or your int swap variable. In fact it looks like it assumed you were referring to the function and tried to somehow convert it to type int. Try renaming your variable to something else.

In general, try to stay away from using directives, to avoid name collisions like this.