简体   繁体   中英

If statement inside Struct Declaration C++

I have a doubt regarding structs and if statements in C++

For the sake of simplicity, I have created a sample code to explain my intention

int var = 10

struct example{
    int a;
    int b;
    if(var > 8){
        int c;
    }
};

I have a codebase which uses similar kind of code as above. Commenting out the if portion does not give any errors. My question is

  • Could if statements be put in struct declarations?
  • If not, what is the possible remedy for this, since if statment is mandatory.

Note: I cannot use #if,#else directives nor std::optional or other standard libraries to mitigate this, so please help me find another solution.

No you can't use if statement inside your struct or class definition. Instead, for condition declaration, you can use #if directive.

#define var 10
struct example {
    int a;
    int b;
    #if var > 8
        int c;
    #endif
}

This will work.

'#if' is a compiler directive (pre-processor directive). if statement on the other hand is runtime statement.

Other than this there is no other way!

int main()
{
    int var = 10;
     if(var>10){
                struct example{
                int a;
                int b;
                int c;

             };
            }else {
                    struct example{
                    int a;
                    int b;

                  };

                }
      cout<<"Hello World";

       return 0;
}

There are multiple ways to address your problem one way of achieving is shown.

We cannot add if Statement in the Structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM