ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 2 · 3లో పాఠం 3కోర్సులో 6/18~8 min
మాడ్యూల్ పాఠాలు (3/3)

స్విచ్ స్టేట్మెంట్

The switch statement allows replacing long chains of if-else if-else statements when comparing a variable against several constant values.

The switch Syntax

The switch statement compares an expression against multiple case labels:

Code
char grade = 'B';

switch (grade) {
    case 'A':
        std::cout << "Excellent!" << std::endl;
        break;
    case 'B':
        std::cout << "Very well!" << std::endl;
        break;
    case 'C':
        std::cout << "Sufficient." << std::endl;
        break;
    default:
        std::cout << "Invalid grade." << std::endl;
        break;
}
  • break: is fundamental. If omitted, execution will fall through into the next cases (a behavior known as fall-through).
  • default: an optional block executed if none of the previous cases match the tested value.

Try it yourself

వ్యాయామం#cpp.m2.l3.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Given an integer day read from std::cin, use switch to print 'lunedi' if day is 1, 'martedi' if it is 2, and 'altro' for any other value.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Structure the switch on `day`by inserting`case 1:`, `case 2:`, and `default:`, remembering the `break` statement at the end of each branch.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

వ్యాయామం#cpp.m2.l3.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Given a variable grade read from std::cin, use a switch to print 'ottimo' for 'A', 'buono' for 'B', and 'insufficiente' for all other cases.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

For characters use single quotes, e.g. `case 'A':`.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది