user@Robert_Solca:~/Programming$

Introduction

Imagine you need to make a decision. How are you going to make it? Well most probably you will verify some conditions in your head. For example if you need to make a decision about going outside you might verify if it's sunny.

if

In programming you will make decisions depending on the data and some results. Most programming languages have the if... else... statement and you usually use it like this:
if (condition){
    ...
} else {
    ...
}
where condition is a logical condition or in some programming languages it can be anything that can be represented as a number (0 will be false, anything else will be true) You don't need to have an else statement too, it's optional

Example

int x = 1;

if (x < 5){
    std::cout<<"x is less than 5";
} else {
    std::cout<<"x is greater or equal to 5";
}
This will print x is less than 5

switch

Some programming languages have a statement called switch that is a lookup table (it's not just if else). If your programming language dosen't have it you can do if else, but won't be as efficient as a switch, or you can do some funky magic with a hash table. The basic syntax is:
switch(expression){
    case constant-expression:
        ...
    case constant-expression:
        ...
    ...
    default:
        ...
}
The default part is optional. That path will be taken if the value wasn't found in the lookup table.

Example

int x = 1;
switch(x){
    case 1:
        std::cout<<"A";
    case 2:
        std::cout<<"B";
    default:
        std::cout<<"C";
}
This will print A. You can use break to skip the remaining verifications

Share this:

facebook twitter google pinterest linkedin email