Search code examples
c++auto

Is it possible to declare auto variables with an if?


My Code is below.

struct conv{
    struct des
    {
        des(int a) {}
        des(int a, int b) {}
        des(int a, int b, int c) {}
    };
};
int main(int argc, const char * argv[]) {

int a = 1;
int b = 1;
int c = 1;

if (a > 1)
{
    auto conv_desc = conv::des(1, 2, 3);
} else if(b > 1) {
    auto conv_desc = conv::des(1, 2);
} else {
    auto conv_desc = conv::des(1);
}
    return 0;
}

The code's pattern is extracted from mkldnn. The only thing I want to do is take auto conv_desc out of the if-else statement. I tried to declare auto conv_desc out of the if-else statement. It occurred an error: Declaration of

variable 'conv_desc' with deduced type 'auto' requires an initializer

Or if I used the pointer like below, I got a null pointer. enter image description here

Another way got an error: enter image description here

Taking the address of a temporary object of type 'conv::des'

If I can't solve this problem, I will have to write a large piece of duplicate code in each branch.


Solution

  • Move your if code into separate function:

    conv::des make_des(int a, int b) {
      if (a > 1) {
        return conv::des(1, 2, 3);
      } else if(b > 1) {
        return conv::des(1, 2);
      } else {
        return conv::des(1);
      }
    }
    
    int main(int argc, const char * argv[]) {
      int a = 1;
      int b = 1;
      int c = 1;
      auto conv_desc = make_des(a, b);
      return 0;
    }