溫馨提示×

c語言swtich如何替代ifelse

小樊
81
2024-10-16 22:30:25
欄目: 編程語言

在C語言中,switch語句可以替代多行的if-else語句,使代碼更加簡潔和易于理解。switch語句根據(jù)一個表達式的值來選擇執(zhí)行多個代碼塊中的一個。下面是一個使用switch替代if-else的示例:

假設我們有以下if-else語句:

int value = 2;

if (value == 1) {
    printf("Value is 1\n");
} else if (value == 2) {
    printf("Value is 2\n");
} else if (value == 3) {
    printf("Value is 3\n");
} else {
    printf("Value is not 1, 2, or 3\n");
}

我們可以用switch語句重寫為:

int value = 2;

switch (value) {
    case 1:
        printf("Value is 1\n");
        break;
    case 2:
        printf("Value is 2\n");
        break;
    case 3:
        printf("Value is 3\n");
        break;
    default:
        printf("Value is not 1, 2, or 3\n");
}

在這個例子中,switch語句根據(jù)value變量的值來選擇對應的case標簽,并執(zhí)行相應的代碼塊。break語句用于退出switch結構,防止代碼執(zhí)行到下一個case。如果沒有匹配的case,且存在default標簽,則會執(zhí)行default中的代碼。

0