TransWikia.com

error: cannot resolve overloaded function based on conversion to type ‘int’

Stack Overflow Asked by purple_tulip on December 13, 2021

I wrote the following code :

#include<bits/stdc++.h>
using namespace std;
int lengthOfLastWord(string A) {
    int m= A.size();
    int i=0;
    while(i<m)
    {
        if(A[i]==' ')
        {
            int count=0;
            i++;
            while(A[i]!=' ')
            {
                count++;
                i++;
            }
        }
        else
        i++;
    }
    return count;
}
int main()
{
    string A;
    getline(cin,A);
    cout<<lengthOfLastWord(A);
}

But it is showing the following error

error: cannot resolve overloaded function ‘count’ based on conversion to type ‘int’

I am unable to understand why is it showing this error and what should I do to fix it.
Please help me.
Thankyou

3 Answers

The most direct reason is because your count variable is defined in the if scope, and not available in the scope of return statement.

However, the error you are seeing is confusing, since you have using namespace std in your code, and it makes completely unrelated (for your purposes) function std::count visible everywhere in your program, including your return statement. From the compiler perspective, you are trying to return a pointer to std::count, but since this function is overloaded template, compiler doesn't know which one you are trying to return - thus the phrasing of the errror.

If you remove the using namespace std from your code, which you should have never had in the first place, your code will still fail to compile, but error message would be way more easier to understand.

Answered by SergeyA on December 13, 2021

One solution is to rename your count variable to something else like total.

The compiler is considering std::count function instead of the count variable which is int.

Answered by Deepak Patankar on December 13, 2021

Inside the if scope, your count variable is colliding with (technically "shadowing") std::count. However, your local count does not exist in the scope of your return statement, so the compiler is trying to use the only count that it knows about at that point, which is std::count.

This is a great example of why using namespace std and #include<bits/stdc++.h> are both bad ideas. If proper includes and namespaces were used, this code would have given you a much clearer compile error:

error: 'count' was not declared in this scope

Answered by 0x5453 on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP