• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

[Solved] Switch statement queries

D

DaMuffin

Guest
Hey all, I have a couple of quick questions.

With the switch statement are you supposed to place "break" inside or outside the curly brackets? I searched the manual (1.4) but the example given doesn't use curly brackets.
I haven't noticed any difference either way so I'm just curious does it matter? Is one way better if you plan on learning other languages?
 
G

Gillen82

Guest
You should place the break at the end of each line of code i.e

Code:
switch ( whatever )
{
    case whatever: code here; break;
    case whatever: code here; break;
    case whatever: code here; break;
    case whatever: code here; break;
}
This will ensure when the correct case has been selected, it will break out of the switch and process any other code in the event.
 

Smiechu

Member
You should place the break at the end of each line of code i.e

Code:
switch ( whatever )
{
    case whatever: code here; break;
    case whatever: code here; break;
    case whatever: code here; break;
    case whatever: code here; break;
}
This will ensure when the correct case has been selected, it will break out of the switch and process any other code in the event.
This is only partally true... this true for a simple situation...
But when you have a big block of code inside, then... basicly you should put break inside the brackets on the end. Becouse the brake statement is a part of the whole case block...
Code:
case 1:
   {


   break;
   }
Second thing... nothing stops you from making 3 or 5 breaks on the begining of the block, i.e. when you want under some circumstances that rest of the block is not executed...
You can also want to use ths switch statement without breaks and make some cascade effect...

But in all cases the break should be inside of the bracets...
 
G

Gillen82

Guest
This is only partally true... this true for a simple situation...
But when you have a big block of code inside, then... basicly you should put break inside the brackets on the end. Becouse the brake statement is a part of the whole case block...
Code:
case 1:
   {


   break;
   }
Second thing... nothing stops you from making 3 or 5 breaks on the begining of the block, i.e. when you want under some circumstances that rest of the block is not executed...
You can also want to use ths switch statement without breaks and make some cascade effect...

But in all cases the break should be inside of the bracets...
Surely having the break outside the block of code is just as effective, regardless of the size of the block. If the switch chooses the correct case, process the code, and then comes to the break (inside or outside) it will have the same effect.
 

samspade

Member
Hey all, I have a couple of quick questions.

With the switch statement are you supposed to place "break" inside or outside the curly brackets? I searched the manual (1.4) but the example given doesn't use curly brackets.
I haven't noticed any difference either way so I'm just curious does it matter? Is one way better if you plan on learning other languages?
The basic answer has already been given, inside the brackets, but I'm not sure that it actually makes a difference in GML as GML doesn't even require you to use brackets for cases in a switch statement. However, I think that it is more helpful to think of break as what it actually is, rather than just in its usefulness in a switch statement, to understand where you should use it. In other words, break is not just a way to end a specific case in a switch statement. Quoting from the manual, "The "break" is used to end prematurely a for, repeat, while, do... until loop of some kind, or to tell a switch statement to end at that point, or to prematurely end a with function."

The reason it is important to think of it this way is that it allows you to do so many more things than just end a switch statement. See, for example outside of a switch statement, the manual on this: https://docs.yoyogames.com/source/d...e/001_gml language overview/401_13_break.html

But it also has other uses in a switch statement. For example:

Code:
switch (something) {
    case 0:
        /* code here */ 
    case 1:
        /* code here */
        break;
}
If something == 0 then what is in both case 0 and case 1 will run whereas if something == 1 then only what is in case 1 will run. Additionally, you may sometimes want to do this:

Code:
switch (case) {
    case 0:
        /* some code */
        if (something_else) {
            /* some more code */
            break;
            }
        /* remaining code */
        break;
}
Here some code in case 0 runs, then it checks an if statement, and if it is true some more code runs AND it exits the case before running the remaining code.

So a more complete answer to your original question is you can put break in a lot of places and your code will do exactly what it is told to, break out of the loop, switch statement, or with statement and continue on. You should decide where to put it based upon what you want to happen, when you want to break out.
 

Neptune

Member
Most of these are really bad formatting for someone trying to learn, so I'll post a switch with some comments.
Code:
switch(integer_variable) //Could also be a string
{
    case 0:
 
        //CODE
    
    break;
 
    case 1:
 
        //CODE
    
    break;

    case "name":

        //CODE
   
    break;
}
You can think of each "case / break" block as the consequent of an "if statement".
 
Last edited:

TheouAegis

Member
Code:
switch n              //this is the variable or non-boolean expression you want to check
{                     //this curly is required

case 4:               //ordering of cases doesn't matter, but should be ordered by probability
        /*code*/
        break;        //this break is the only thing telling the program the case has ended

case 0:
case 1:               //Cases 0 and 1 are identical here
       /*code*/
       break;

case 3:               //Case 3 will run both its code and case 2's code
      /*code*/
case 2:               //Case 2 will only run its code
      /*code*/
      break;

case 5:               //case 5 will run its code, 6's code, and 7's code
      /*code*/
case 6:               //case 6 will run its code and 7's code
      /*code*/
case 7:               //case 7 will only run its code
      /*code*/
                      //there are no more cases, so break isn't required here

}

The location of the break doesn't matter as long as it's placed logically.

Code:
switch n
{

case 0: if vspeed < 0 break;
        if place_meeting(x,y+vspeed,platform)
        while !place_meeting(x,y+1,platform)
            y+=1;
        break;

case 1: hspeed += 1;
case 2: vspeed += 1;
        break;

case 3: n = 0;

}

if --timer == 0 
{
  n++;
  timer = (irandom(29)+1)*2;
In case 0, if vspeed is negative, then the collision check won't run because the case will break.

In case 1, hspeed will increase; since there is no break, it progresses to cases 2 and increases vspeed as well.

In case 2, only vspeed increases and then it breaks.

In case 3, n is set to 0 so that the next time the switch is called case 0 will be run. The case then ends because there is no more code within the switch.

After any case has been run, the timer variable is decreased and if it's 0 the value of n increases so that the next time the switch is called it will run the next case and the timer is reset to a random duration between 2 and 60 steps.
 
Last edited:
S

SarbjitGrewal

Guest
Always place curly braces outside from the case to define which condition will be executed. Thank You.!
 

csanyk

Member
Here's how I do my switches:

Code:
switch (expression)
{
    case a:  {
                 //do case a stuff;
                 break;                 
             }

    case b:  {
                 //do case b stuff;
                 break;
             }

    default: {
                //does anyone ever use default?
                //break;
             }
}
 

TheouAegis

Member
Here's how I do my switches:

Code:
switch (expression)
{
    case a:  {
                 //do case a stuff;
                 break;                
             }

    case b:  {
                 //do case b stuff;
                 break;
             }

    default: {
                //does anyone ever use default?
                //break;
             }
}
I use default quite a bit. Type out 2, 3 or more cases, each of which have to be analyzed? Or use default? Remember a switch is basically just if then else then if then else. If you have a final else, then you'd use default.
 

Simon Gust

Member
I like this design
Code:
switch (expression)
{
    case 0: // desc 0
    {
        // execution 0
    }
    break;
    case 1: // desc 1
    {
        // execution 1
    }
    break;
    case 2: // desc 2
    {
        // execution 2
    }
    break;
}
 

TheouAegis

Member
You waste so much time and space using semicolons. You can shorten your code quite a bit by taking out all of those semicolons. Geez


Note to newbies: sometimes we post bad advice as jokes on these forums. Be advised.
 

TheouAegis

Member
Well depending on what he has in place of "code here" he could leave out spaces AND semicolons. Certain characters count as code syntax breaks.
 

CloseRange

Member
this is why switch statements suck in all honestly just use if else:
Code:
if case_1 CODE HERE else if case_2 CODE_HERE else if case_3 CODE HERE if else IM LOST
 

TheouAegis

Member
if n==1 or n==2
{
blahblahblah;
if n==2
{
blahblahblah;
}
}

Switches aren't all bad. You'd have to check n twice with the code above. With a switch, it'd only be checked once.


Also your code has a slight problem in that case_1 and case_2 and case_3 are all booleans. You don't use switches with booleans, you use them with variables that have many possible values.

if n==case_21 then code
else if n==case_2 then code
else if n==case_3 then code

You checked n 3 times, whereas a switch is meant to check n only once.

...But I think there was a flaw with the code logic in GM. I can't remember off the top of my head. But yeah, a switch is conceptually faster.
 

CloseRange

Member
if n==1 or n==2
{
blahblahblah;
if n==2
{
blahblahblah;
}
}

Switches aren't all bad. You'd have to check n twice with the code above. With a switch, it'd only be checked once.


Also your code has a slight problem in that case_1 and case_2 and case_3 are all booleans. You don't use switches with booleans, you use them with variables that have many possible values.

if n==case_21 then code
else if n==case_2 then code
else if n==case_3 then code

You checked n 3 times, whereas a switch is meant to check n only once.

...But I think there was a flaw with the code logic in GM. I can't remember off the top of my head. But yeah, a switch is conceptually faster.
I was making a joke just to make the code more confusing :p
but because you bring it up actually yes switch functions use Boolean. In fact there is no such thing as a "case"/"function"/"if statement" that doesn't go based on a boolean:

Take for example:

Code:
var bool = (variable == 2);
if bool {
   
}
variable isn't a boolean but when you are comparing 2 variables (or a variable and a constant) it is still thought of as true or false:

if variable > 0

this will either be true or false based on if 'variable is more than 0

a switch statment does this:
Code:
switch variable:
     case (if variable == 1): Do Code; break;
     case (if variable == 2): Do Code; break;
     case (if variable == 3): Do Code; break;
this makes switch statment's just the same as a bunch of If statments UNLESS you do this:
Code:
var variable = a_variable * another_variable + 76;
switch (variable) {
    
}
because then it doesn't have to calculate that huge equation every time
 

TheouAegis

Member
a switch statment does this:
Code:
switch variable:
case (if variable == 1): Do Code; break;
case (if variable == 2): Do Code; break;
case (if variable == 3): Do Code; break;
If switches were coded in GM to actually behave like that, then they wrote their compiler wrong and ruined switches completely. A switch is by its very nature supposed to compile with only one single variable call and inherently be faster than an if-else tree in all cases. I wouldn't be surprised if GM was coded improperly in that regard, but in a language with a proper compiler, a switch would be faster.
 

CloseRange

Member
ill admit switches to run faster but on such a microsopic level you might as well say they are the same. What I said is how switches run in all applications because computers litteraly run on 1's and 0's (true and falses). However a switch uses a special thing called a hash table (I'm pretty sure that's what it's called) and it makes it run slightly faster.
The main reason to use switch isn't for a faster performace but: if you are using arrays, constants, or just want a cleaner script.

That's really what it boils down to is switches are easier to read than a bunch of if else statments. But if else statments also allow more control if you can keep up with the clutter.
 
I know this is an old thread, but here's a switch-related learning that might come in handy.

Let's say that you want to run the same code for a specific case or the default case, well, it is possible to use case OR with your specific case and the default case. This will help you avoid while loops, etc. to ascertain when/how the code should proceed. Just do this:


Code:
    switch(someInput)
    {
        //Main case or a case beyond scope
        case a:
        default:
        {
            //...
        }
        break;
       
        case b:
        {}
        break;

        case c:
        {}
        break;
        //. . .
        case n:
        {}
        break;
    }
Perfect! No need to run separate code if default and a specific case should perform the same operation.

Hope that comes in handy for someone in the future!
 
Last edited:

CloseRange

Member
well default encompass anything that wasn't specified by any other case....
if you just chose to not include the case a: at all then it will do the same thing:
Code:
switch(condition) {
     case b: break;
     case c: break;
     default:
          // will include case 'a' still
}
well at least that's the case with default but if you use case b: case c: break then that's another story.
Code:
switch(condition) {
     case a:
     case b:
         // if a OR b
         break;
     case c:
         break;
}
but I feel like that's already well known and explained in the docs
 

TheouAegis

Member
I know this is an old thread, but here's a switch-related learning that might come in handy.

Let's say that you want to run the same code for a specific case or the default case, well, it is possible to use case OR with your specific case and the default case. This will help you avoid while loops, etc. to ascertain when/how the code should proceed. Just do this:


Code:
    switch(someInput)
    {
        //Main case or a case beyond scope
        case a:
        default:
        {
            //...
        }
        break;
      
        case b:
        {}
        break;

        case c:
        {}
        break;
        //. . .
        case n:
        {}
        break;
    }
Perfect! No need to run separate code if default and a specific case should perform the same operation.

Hope that comes in handy for someone in the future!
This was actually covered up in post #7 of this thread, along with case sharing and exclusivity.
 

TheouAegis

Member
Right, but "default" wasn't in there. Might have confused some folks. I always thought "default" had to come at the end.
True... I actually thought your code was faulty, but maybe GM's compiler sorts the switch, because it worked for me too. Then again, as was stated, your example had no use for case 0 since it was 100% the same as default. You should have given case 0 exclusive code that then ran on into default.

If you have both compilers, verify default can still appear at the top with all compilers. But at least for the main runner, it works. Good catch.
 

Neptune

Member
This dang post lol
Code:
switch(sswitch){
case 0: {
my_codes ++;                              }break;
          case 1:{
          my_codes2 --;  
}break;
}
 
Top