Home > Back-end >  Need help struct-void error: type name isn't allowed
Need help struct-void error: type name isn't allowed

Time:09-22

I created a struct and void function. I want to write out age and name inside of struct xyz with the void abc. But i didn't understand i'm getting an error on case 1-2 part

type name isn't allowed

#include <iostream>
using namespace std;

struct xyz {
    int age = 20;
    string name = "name";
};
void abc() {
    int num;
    cin >> num;
    switch (num) {
    case 1: cout << xyz.age << endl;
        return;
    case 2: cout << xyz.name << endl;
        return;
    }
}
int main()
{
    for(;;)
    abc();
}

CodePudding user response:

You'd have to do something like this -

#include <iostream>
using namespace std;

struct xyz {
    int age = 20;
    string name = "name";
};
void abc() {
    xyz myStruct;
    int num;
    cin >> num;
    switch (num) {
    case 1: cout << myStruct.age << endl;
        return;
    case 2: cout << myStruct.name << endl;
        return;
    }
}
int main()
{
    for(;;)
        abc();
}

Another option would be something like this -

#include <iostream>
using namespace std;

struct xyz {
    int age;
    string name;
};
void abc() {
    xyz myStruct{20, "name"};
    int num;
    cin >> num;
    switch (num) {
    case 1: cout << myStruct.age << endl;
        return;
    case 2: cout << myStruct.name << endl;
        return;
    }
}
int main()
{
    for(;;)
        abc();
}

CodePudding user response:

You don't have created an instance of your type i.e. struct xyz, lets create one named static_instance and fix your code to something close what you seem to have intended

#include <iostream>
#include <string>

struct xyz {
    int age = 20;
    std::string name = "name";
} static_instance;

void abc() {
    int num{};
    std::cin >> num;
    switch (num) {
        case 1:
            std::cout << static_instance.age << "\n";
            break;
        case 2:
            std::cout << static_instance.name << "\n";
            break;
    }
}

int main() {
    while (true) {
        abc();
    }
}

Be aware that you seem to lack many basic principles of C , for first improvements, that function abc should either be a member method or take a reference to your struct. Also prefer "stack" or automatic storage variables i.e. instances before static i.e. global ones. Like

#include <iostream>
#include <string>

struct xyz {
    int age = 20;
    std::string name = "name";
};

void print(const xyz& instance) {
    int num{};
    std::cin >> num;
    switch (num) {
        case 1:
            std::cout << instance.age << "\n";
            break;
        case 2:
            std::cout << instance.name << "\n";
            break;
    }
}

int main() {
    xyz instance{};
    while (true) {
        print(instance);
    }
}
  •  Tags:  
  • c
  • Related