Thread: Exit from the switch-case

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    1

    Exit from the switch-case

    My progg is calling a function from one case of a switch. Now in that function if a condition matches, I want to come out of the switch directly from the fn itself.


    switch(x)
    {
    case 01:
    -------
    -------
    fn();
    ------
    --------
    break;

    -----
    -----
    }

    fn()
    {
    ------
    -----
    -----
    if(condn)
    {
    exit from the switch
    }
    else
    {
    -----
    }

    -----
    ------
    }

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    You can't exit a switch from inside a function.

    The only way you're gonna be able to do that is to have the function return a value, and then check the return value of the function, and exit the switch from there.

    Edit: Dang. Beaten.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Im a Capricorn vsriharsha's Avatar
    Join Date
    Feb 2002
    Posts
    192

    Red face Wont a GOTO work?

    how about using a GOTO statement in the function? will it work if used cautiously?

    -Harsha.
    Help everyone you can

  4. #4
    Registered User Casey's Avatar
    Join Date
    Jun 2003
    Posts
    47
    >how about using a GOTO statement in the function?
    goto can't span two functions, the label and the goto have to be in the same function. You can use setjmp and longjmp, but IMHO that's a little too awkward.
    Code:
    #include <stdio.h>
    #include <setjmp.h>
    
    jmp_buf jbuf;
    
    void fn()
    {
        longjmp(jbuf, -1); /* Exit switch */
    }
    
    int main(void)
    {
        int c = 0;
    
        if (setjmp(jbuf) == 0)
        {
            puts("Start");
    
            switch (c)
            {
            case 0:
                fn();
                break;
            }
        }
        else
            puts("End");
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Number to Word (Billions)
    By myphilosofi in forum C Programming
    Replies: 34
    Last Post: 02-04-2009, 02:09 AM
  3. Base converter libary
    By cdonlan in forum C++ Programming
    Replies: 22
    Last Post: 05-15-2005, 01:11 AM
  4. Strings and Switch Statement
    By Ajsan in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2004, 01:16 PM
  5. rand()
    By serious in forum C Programming
    Replies: 8
    Last Post: 02-15-2002, 02:07 AM