操作系统:Windows10 编译器:gcc 12.2.0 github仓库链接: https://github.com/Nazarite31/ClangTutorial/tree/main/fromEntryToAdvanced/ch2

if语句

#include <stdio.h>

// 什么是语句?
// C语言中由一个分号;隔开的就是一条语句
;  // 空语句

// 分支语句(选择结构)


int main(int argc, char *argv[])
{
    int age;
    printf("input your age:\n");
    scanf("%d", &age);

    if (age < 18)
        printf("You are underage.\n");

    if (age < 18)
    {
        printf("You are underage.\n");
        printf("You can't fall in love.\n");
    }
    else if (age >= 18 && age < 28)
        printf("You are youth.\n");
    else if (age >= 28 && age < 50)
        printf("You are in your prime.\n");
    else if (age >= 50 && age < 70)
        printf("You are elderly.\n");
    else
        printf("You are old.\n");

    // 悬空else问题:else和离它最近的未匹配的if匹配,和缩进无关

    // 判断变量与常量是否相等时把常量放在左边 5 == num ,避免num = 5的bug产生

    return 0;
}

switch语句

#include <stdio.h>


int main(int argc, char *argv[])
{
    int day;

    printf("input a number(1-7): ");
    scanf("%d", &day);

    switch (day)  // switch后必须是整型表达式!
    {
        case 1:  // case后必须是整型常量表达式!
            printf("Monday\n");
            break;  // 搭配break语句实现分支
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:   // default不一定要写在最后
            printf("%d is illegal number\n", day);
            break;
    }

    switch (day)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            printf("working day\n");
            break;
        case 6:
        case 7:
            printf("rest day\n");
            break;
        default:
            printf("%d is illegal number\n", day);
            break;
    }

    return 0;
}

while循环

#include <stdio.h>


int main(int argc, char *argv[])
{
    int i = 1;

    while (i < 11)
    {
        printf("%d ", i);
        ++i;
    }
    printf("\n");

    return 0;
}
#include <stdio.h>


int main(int argc, char *argv[])
{
    int ch = 0;

    // 输入Ctrl+z代表EOF
    // EOF(end of file),值是-1
    while ((ch = getchar()) != EOF)
    {
        putchar(ch);
    }

    return 0;
}