0

Can I print the element names of a structure in C++?

Example: If I have the structure in my code as

struct Info {
uint8_t ID;
uint8_t Weight;
uint8_t Time[3];
}

I want my console to print the text below without hard-coding them. I want it to be extracted from the struct. Is this possible?

ID, Weight, Time0, Time1, Time2

Note: not the value of ID or what not. I would want the console to print the words "ID, Weight... etc". It will be used as field names for a file.

Nard
  • 45
  • 1
  • 6
  • 1
    Just checking, should this be retagged as C code? – JVApen Jun 29 '20 at 08:13
  • 1
    Keyword is reflection. You may either implement it yourself or seek for a library. Related: https://stackoverflow.com/a/88215/4123703 – Louis Go Jun 29 '20 at 08:13
  • @JVApen No, I am working on c++ but my header files are formatted that way, so i have the example struct like that :) – Nard Jun 29 '20 at 08:16
  • 1
    @Nard Go through this thread: [visual c++ - Printing values of all fields in a C++ structure - Stack Overflow](https://stackoverflow.com/questions/2758937/printing-values-of-all-fields-in-a-c-structure). – brc-dd Jun 29 '20 at 08:17
  • @Nard I would recommend writing `struct Name { int ID; .. };` instead if you are using c++. I know sufficient professional C++ programmers that can't read your code – JVApen Jun 29 '20 at 08:21

1 Answers1

0

Variable names are identifiers, after compilation they do not exist in the compiled executable. You cannot print them in a regular C++ application.

But if you want to create the output yourself it would look like this:

struct Info {
    uint8_t ID;
    uint8_t Weight;
    uint8_t Time[3];
};

int main()
{

    Info infoObj;
    infoObj.ID = 1;

    std::cout << "infoObj.ID = " << infoObj.ID << std::endl;

    std::getchar();

    return 0;
}
GuidedHacking
  • 3,628
  • 1
  • 9
  • 59