Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære The Keyword Default | Conditional Statements
Introduction to C++

bookThe Keyword Default

To specify the code to execute if there is no case match, you can use default keyword in switch statement. For example, the coffee machine has a list of types of coffee by its number (from 1 to 3). If you want to choose one, just type its number. But there is a huge amount of numbers that users can type by mistake. Here we can use the default keyword:

// Declare and assign the variable
int number;
cin >> number;

// Choose coffee
switch (number) {
    case 1:
        cout << "Espresso";
        break;
    case 2:
        cout << "Latte";
        break;
    case 3:
        cout << "Cappuccino";
        break;
    default:
        cout << "Your number isn't valid. Please, try again.";
}

The default statement executes the code when the non of statements are true.

The default statement must be at the end of the switch.

question-icon

Fill the gaps:

The `default` keyword specifies some code to runand it.

Click or drag`n`drop items and fill in the blanks

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 9

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Awesome!

Completion rate improved to 3.33

bookThe Keyword Default

Sveip for å vise menyen

To specify the code to execute if there is no case match, you can use default keyword in switch statement. For example, the coffee machine has a list of types of coffee by its number (from 1 to 3). If you want to choose one, just type its number. But there is a huge amount of numbers that users can type by mistake. Here we can use the default keyword:

// Declare and assign the variable
int number;
cin >> number;

// Choose coffee
switch (number) {
    case 1:
        cout << "Espresso";
        break;
    case 2:
        cout << "Latte";
        break;
    case 3:
        cout << "Cappuccino";
        break;
    default:
        cout << "Your number isn't valid. Please, try again.";
}

The default statement executes the code when the non of statements are true.

The default statement must be at the end of the switch.

question-icon

Fill the gaps:

The `default` keyword specifies some code to runand it.

Click or drag`n`drop items and fill in the blanks

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 9
some-alt