'Why am I getting error "reference to struct_tag is ambiguous" with using namespace std? [duplicate]

I was trying to write a function with a return type of struct variable. If I use using namespace std; I get an error but if instead use std:: the program runs fine.

The erroneous code:

#include<iostream>
using namespace std;

struct distance
{
    int feet;
    int inches;
};
distance foo(distance, distance);
int main()
{
    distance d1, d2;
    cout << "Input feet of d1: ";     cin >> d1.feet;
    cout << "\nInput inches of d1: "; cin >> d1.inches;
    cout << "\nInput feet of d2: ";   cin >> d2.feet;
    cout << "\nInput inches of d2: "; cin >> d2.inches;
    distance large = foo(d1, d2);
    cout << "The larger distance is: " << large.feet << "\'-" << large.inches << "\"";
}
distance foo(distance d1, distance d2)
{
    float temp1 = d1.feet + d1.inches/12;
    float temp2 = d2.feet + d2.inches/12;
    if(temp1>temp2) return d1;
    else return d2;
}

Error: Reference to distance is ambiguous.

Working code without namespace std:

#include<iostream>

struct distance
{
    int feet;
    int inches;
};
distance foo(distance, distance);
int main()
{
    distance d1, d2;
    std::cout << "Input feet of d1: "; std::cin >> d1.feet;
    std::cout << "\nInput inches of d1: "; std::cin >> d1.inches;
    std::cout << "\nInput feet of d2: "; std::cin >> d2.feet;
    std::cout << "\nInput inches of d2: "; std::cin >> d2.inches;
    distance large = foo(d1, d2);
    std::cout << "The larger distance is: " << large.feet << "\'-" << large.inches << "\"";
}
distance foo(distance d1, distance d2)
{
    float temp1 = d1.feet + d1.inches/12;
    float temp2 = d2.feet + d2.inches/12;
    if(temp1>temp2) return d1;
    else return d2;
}

As far as I know namespace std has objects like cout, cin etc. But what does it have to do with structures? Why does using namespace std give error while directly using std:: runs the program smoothly?



Solution 1:[1]

As the message sugggests, the name distance is ambigious between std::distance and the structure you defined.

You can write

using std::cin;
using std::cout;
// more using for identifiers from namespace std to use

instead of using namespace std;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikeCAT