Thread: switches and classes... so very very confused :( plz clarify

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    47

    switches and classes... so very very confused :( plz clarify

    would really appriciate someone clarifying a couple of questions for me..

    first question:
    I typed this code in
    Code:
    #include<iostream>
    using namespace std;
    
    char input[101];
    
    class a_class
    {
    	char* first;
    	char* second;
    
    	public:
    		a_class(){
    			cout << "What is your first input ?\n";
    			cin.getline(input, 100);
    			this->first = new char[strlen(input) + 1];
    			strcpy(this->first, input);
    
    			cout << "What is your second input ? ";
    			cin.getline(input, 100);
    			this->second = new char[strlen(input) + 1];
    			strcpy(this->second, input);
    		}
    		~a_class(){};
    };
    
    void main(){
    int slct;
    do{
    	cin >> slct;
    	switch ( slct ) 
    	{
    		case 0 :
    			break;
    
    		case 1 :
    			cout << "You picked 1" << endl;
    			a_class a;
    			break;
    
    		case 2 : 
    			break;
    
    		default :
    			break;
    	}
    }while (slct != 5);
    }
    and got the error
    Code:
    initialization of 'a' is skipped by 'case' label
    i found out that to solve this error i had to put brackets around
    Code:
     {
                            cout << "You picked 1" << endl;
    			a_class a;
    			break;
                            }
    can someone plz clarify to me in simple terms, why the brackets are needed.


    Second:
    After adding the brackets and inputing "1" as the switch, I get the following.
    Code:
    You picked 1
    What is your first input ?
    What is your second input?
    the problem with this is that i wasn't able to input my "first input" in the first place.. it just skipped the 'cin' and went to the next one..

    Please explain why this is happening and how i can fix it.
    Replies are greatly appriciated!!!!!

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    can someone plz clarify to me in simple terms, why the brackets are needed.
    Otherwise a would not go out of scope until the end of the switch, it would sort of be possible to reach code using a without constructing it.

    Similarly:
    Code:
        if (x) goto skip;
        std::string s;
    
    skip:
        s = "Hello";
    If this was allowed, we might end up storing "Hello" in a string object that was never constructed (if x is true).

    the problem with this is that i wasn't able to input my "first input" in the first place.. it just skipped the 'cin' and went to the next one..
    operator >> leaves newline (and any other unread characters) in the stream, so the first getline has something to read (in effect, if the input stream was empty, you'd get the same effect by pressing Enter at that place).
    Solution is to clear to stream (should be in a FAQ).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Because in case 2: you might have written:
    Code:
    case 2:
    cout << a.first << endl;
    Which will probably crash when slct equals 2 because as it says, it skips initialisation of a. When you add the extra brackets you can't write the above in case 2, so it knows there can never be a problem.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    May 2008
    Location
    Paris
    Posts
    248
    Otherwise a would not go out of scope until the end of the switch
    that's pretty annoying: I think a temporary should be allowed if it is not used out side its case...

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by MarkZWEERS View Post
    that's pretty annoying: I think a temporary should be allowed if it is not used out side its case...
    It is, as long as you make it local scope - the problem is that in a
    Code:
    switch(xx)
    {
    ...
    }
    the whole switch statement is one large scope - so if you declare a variable in the middle, it's the same as if you declared a variable on the other side of a goto as described above - it will not be constructed because you don't run the constructor code, and unconstructed objects aren't a particularly good idea.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    While we're on the subject, let's discuss some other things.
    First, if you don't know, I'd suggest you actually read up on what classes are.
    Second, input should be a local array, not global.
    Void main is undefined. Don't use it.
    You allocate with new, but you never free with delete. Free in the destructor.
    And you should probably indent the code in main once more so it's +1 level than the main function header itself.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Nov 2007
    Posts
    47
    thanks Elysia for you concern, but i'm already aware of all those things you have mentioned. I just was looking for the answer to a particular question.

    As for the answers that everyone has sent, I'm understanding a little bit, but would still like clarification, for my personal knowledge.

    so does the following code:

    Code:
    		case 1 :
    			cout << "You picked 1" << endl;
    			a_class a;
    			break;
    resemble an if statement that is written as so:
    Code:
    If (a > 0)
         a++;
         a--;
    else
         cout << "do nothing" << endl;
    in this case the
    Code:
    a--
    would be skipped in the same way the
    Code:
    a_class a
    ; did; As i understand it.
    If thats the case why does the
    Code:
    break"
    statement not get skipped?


    Second:
    I understand there is something in the buffer which is why it skips the first cin.. where in my code did i leave something in the buffer? and isn't cin supped to empty buffer before expecting an input??


    I apologize for the questions which might seem a little newb, but Im relatively new and would rather understand what the problems are then just know how to fix them..

    I appriciate all the help. thank you.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No, the a_class a; will not be skipped. Once a case is matched in a switch, control jumps to that point and keeps on going until the end of the switch or it encounters a break (or a return, or an exception is thrown, etc).

    EDIT:
    Consider a typical use of a switch:
    Code:
    switch (x)
    {
    case 1:
        foo1();
        foo2();
        break;
    case 2:
    case 3:
        bar();
        break;
    default:
        baz();
    }
    The above is functionally equivalent to:
    Code:
    if (x == 1)
    {
        foo1();
        foo2();
    }
    else if (x == 2 || x == 3)
    {
        bar();
    }
    else
    {
        baz();
    }
    Incidentally, we have a tutorial section that includes a tutorial on this very topic, if I remember correctly.

    I understand there is something in the buffer which is why it skips the first cin.. where in my code did i leave something in the buffer? and isn't cin supped to empty buffer before expecting an input??
    You left whitespace in the buffer with the use of formatted input (operator>>). If the use of formatted input emptied the buffer, then you would find that reading a string of words would only leave you with one word, since the rest would be gone as soon as you had read the first one. As such, you are responsible for ignoring what's left in the buffer, e.g., with the use of cin.ignore().
    Last edited by laserlight; 08-28-2008 at 07:29 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The switch limitation doesn't apply only to classes. You can't declare any variable in a way that it is possible for code execution to skip the declaration to a place where the variable is technically in scope (this can happen with goto and switch). If you want to declare variables within a case, you have to enclose it in {} to make sure that it's scope ends where the case ends.

    where in my code did i leave something in the buffer?
    Code:
    cin >> slct;
    This leaves (at least) the newline that came when you pressed Enter left to be read. That's the way >> works.

    Therefore, after using >> and before using getline, you must empty the stream.

    Code:
    cin.ignore();
    This would clear one unread character.

    Code:
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    This would clear everything up to and including a newline.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  10. #10
    Registered User
    Join Date
    Nov 2007
    Posts
    47
    awesome...
    I'm pretty sure i get it now. Thanks for the help.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MegaManZZ View Post
    thanks Elysia for you concern, but i'm already aware of all those things you have mentioned. I just was looking for the answer to a particular question.
    Alright, good to know!

    Code:
    If (a > 0)
         a++;
         a--;
    else
         cout << "do nothing" << endl;
    in this case the
    Code:
    a--
    would be skipped in the same way the
    Code:
    a_class a
    ; did; As i understand it.
    If thats the case why does the
    Code:
    break"
    statement not get skipped?
    Incidentally, I'm not sure if a-- is skipped here, but I can't be sure. It might depend on how the compiler generates code.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    this:
    Code:
    If (a > 0)
         a++;
         a--;
    else
         cout << "do nothing" << endl;
    should be formatted as:
    Code:
    If (a > 0)
         a++;
    a--;
    else
         cout << "do nothing" << endl;
    Since you now have an "else without an if", the compiler will complain about that, and there will be no code generated. "Syntax Error"

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Incidentally, I'm not sure if a-- is skipped here, but I can't be sure. It might depend on how the compiler generates code.
    I think it will just result in a syntax error.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I suppose that's possible too. Never tried, from what I can remember.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Elysia View Post
    I suppose that's possible too. Never tried, from what I can remember.
    It's not just possible, it's certain. If you have "if" without braces, then the next statement is part of the "true" branch. To have an else-statement, that MUST be the next statement after the true-branch - any further statements will be taken as "no else". If the compiler then finds an else somewhere floating about in the code it will say something along the lines of "unexpected else".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed