What is wrong with this use of namespace in a multiple value return?

Aug 3, 2016 at 1:58am
I am trying to return multiple values of a function using structure. I also want to add namespace to the function but this result an error

error: variable 'main()::t n' has initializer but incomplete type

Full code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

namespace foo
{
struct t
{

    std::string a,b,c;
};

struct t bong(std::string d)
{
    struct t result;

    result.a="hello"+d;
    result.b="caio"+d;
    result.c="namaste"+d;
    return result;
}
}

int main()
{
    struct t n= foo::bong(" world");
    std::cout<<n.a<<endl;
    std::cout<<n.b<<endl;
    std::cout<<n.c<<endl;
}
Last edited on Aug 3, 2016 at 2:00am
Aug 3, 2016 at 2:07am
In C++ you do not have to use the "struct" keyword to declare a structure. In C, you do.

struct t n:

Because you didn't specify that you meant the type foo::t, you inadvertently declared a new anonymous struct named t, local to the main function (that's the ::main():: in the error message). That anonymous struct has no definition, so that's why it's an "incomplete type".

In other words, you've said n's type is some anonymous structure that's totally different than the one defined in ::foo.

Write
struct foo::t n = foo:: bong (" world"); or just foo::t n = foo:: bong (" world"); to get what you want.
Last edited on Aug 3, 2016 at 2:08am
Aug 3, 2016 at 2:17am
Thanks for the explanation
Topic archived. No new replies allowed.