Switch Statements

Suleiman Abdullah

--

Objective: Switch Statements

Switch statements are just like if condition, but are more clean.

We define switch statement starting with switch key word double parentheses ,open and closing curly bracket. Inside the curly bracket we need to use case key word then provide a value to check if case is match with condition variable but in every case must end with colon, then use break to end the case execution when the code between case and break executed.

Why case with number.

Case used to identify if condition variable has value of 1,if this is true the code between case and break will run if false it will jump to the next case.

In the below example when we say case 1: this mean is apple == 1 now ,if true we run code before break for case 1.If false we move to the below case ,if no case match the expression we run default case.

int apples =3;
switch(apple)
{
case 3:
//player press A make player eat 1 apple(This is a comment not code
apples = apples -1;
break;
case 2:
//apples -1 is equal to apple--
apples--;
break;

case 1:
apples--;
break;

default:
apples=0;
break;
}

switch statement is not limited to number we can use to check bool or any other variable type. Here is the bool variable.

Lets use our health variable .

see you in the next article.

--

--

Suleiman Abdullah
Suleiman Abdullah

Written by Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development

No responses yet