-5

Why can't I do this:

struct sName {
  vector<int> x;
};

It takes only three pointers to store a vector, so I should be able to do this?

Prasoon Tiwari
  • 840
  • 2
  • 12
  • 23

3 Answers3

3

You mentioned this failed in a switch statement. You'll need to wrap it up in an extra pair of braces:

int type = UNKNOWN;
switch(type)
{
  case UNKNOWN:
    cout << "try again" << endl;
    break;
  case KNOWN:
  { // Note the extra braces here...
    struct sName
    { 
      vector<int> x;
    } myVector; 
  } // and here
}

Alternatively, you could have already declared the structure, and are just trying to declare and initialize a local variable. This isn't a problem unique to struct, it'll happen anytime you try to initialize a variable inside a case:

struct sName
{ 
  vector<int> x;
};

int type = UNKNOWN;
switch(type)
{
  case UNKNOWN:
    cout << "try again" << endl;
    break;
  case KNOWN:
  { // Note the extra braces here...
    sName myVector;
  } // and here
  case OTHER:
    int invalid = 0; // this will also fail without the extra pair of braces
    break;
}
Community
  • 1
  • 1
Bill
  • 14,257
  • 4
  • 43
  • 55
  • I have seen this reason before, but why? And this works but I don't like this "work around". – Prasoon Tiwari Mar 03 '10 at 16:47
  • @prasoon: all `case`s within a switch are in the same scope. A variable declared in any of them is in the scope of all of them, but the initialization could be skipped. See http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement – Bill Mar 03 '10 at 16:56
  • 1
    @parasoon99: It's not a workaround -- it is leveraging the features of the language in a way that was intended and is valid. It's just something you're not used to. I do this all the time. – John Dibling Mar 03 '10 at 17:00
2
#include <vector>

using namespace std;

struct sName {
  vector<int> x;
};

int main()
{
return 0;
}

Compiled with:

g++ -Wall 1.cpp

Compiled fine.

What seems to be the problem with your code?

Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
  • When I declare a variable of this type "struct sName z" inside a switch statement, I get errors: cross initialization of 'sName z' and 'jump to case label'. Otherwise, the program works fine. – Prasoon Tiwari Mar 03 '10 at 16:32
  • @parasoon99: That's a totally different problem. Create a new post with the new problem, but this time *include the compiler errors* – John Dibling Mar 03 '10 at 16:36
  • @John: Couldn't the OP (or anyone) just edit the question to reflect the actual problem? – Bill Mar 03 '10 at 16:48
0

You can do this. In fact, what you have above is correct and works fine (aside from the missing semicolon and potentially missing std:: in std::vector). Please, rephrase your question so that it doesn't contradict itself.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765