Home > Back-end >  Add member to blank struct? c
Add member to blank struct? c

Time:08-19

I'd like to add members to a struct after its definition. Any way I can do something like this?

struct ss {};
ss.name = ""; //add a string member
ss.age = 0; //add an int member
    
cout << ss.name << "," << ss.age;

CodePudding user response:

No, you can't do it in C . C is a statically typed language. Types are defined in compile time.

But you can use std::map to store key value pairs if you like. Something like this will work for you:

std::map<std::string, std::variant<int, std::string>> ss;
ss["name"] = std::string("");
ss["age"]  = 0;
std::cout << std::get<std::string>(ss["name"]) << ","
    << std::get<int>(ss["age"]) << std::endl;

CodePudding user response:

Any way I can do something like this?

No, there is no way to do this in C . That's not how c works. In particular, struct ss = {}; is not even valid syntax.

struct ss = {}; // invalid syntax in c  

When we provide a definition for struct ss say by writing struct ss{};, then we're telling the compiler(at compile time) that there aren't any members.

If you want to have members name and age then you'll have to provide them inside the class definition:

struct ss 
{
    std::string name;
    int age = 0; 
};

int main()
{
    ss obj;
    std::cout << obj.name <<std::endl;
    std::cout << obj.age << std::endl;
}
  • Related