美文网首页
[习题10]switch

[习题10]switch

作者: AkuRinbu | 来源:发表于2018-09-15 13:41 被阅读9次

使用教材

《“笨办法” 学C语言(Learn C The Hard Way)》
https://www.jianshu.com/p/b0631208a794

switch

  • C语言中的switch语句,可以接受的是结果为整数的表达式,而不是任意的布尔表达式;
  • Rubyswitch语句则可以接收任何布尔表达式;
  • Python没有switch语句;

ex10.c

#include <stdio.h>

int main(int argc,char *argv[])
{
    if(argc!=2) {
        printf("ERROR: You need on arguments.\n");
        //this is how you abort a program
        return 1;
    }

    int i = 0;
    for(i = 0; argv[1][i]!='\0';i++) {
        char letter = argv[1][i];

        switch(letter) {
            case 'a':
            case 'A':
                printf("%d: 'A'\n", i);
                break;

            case 'e':
            case 'E':
                printf("%d: 'E'\n", i);
                break;

            case 'i':
            case 'I':
                printf("%d: 'I'\n", i);
                break;

            case 'o':
            case 'O':
                printf("%d: 'O'\n", i);
                break;

            case 'u':
            case 'U':
                printf("%d: 'U'\n", i);
                break;

            case 'y':
            case 'Y':
                if(i > 2) {
                    // it's only sometimes y
                    printf("%d: 'Y'\n", i);
                }
                break;

            default:
                printf("%d: %c is not a vowel\n", i, letter);
        }
    }

    return 0;
}

Makefile

CC=clang
CFLAGS=-Wall -g

clean:
    rm -f ex10

run

anno@anno-m:~/Documents/mycode/ex10$ make ex10
clang -Wall -g    ex10.c   -o ex10
anno@anno-m:~/Documents/mycode/ex10$ ./ex10
ERROR: You need on arguments.
anno@anno-m:~/Documents/mycode/ex10$ ./ex10 hello
0: h is not a vowel
1: 'E'
2: l is not a vowel
3: l is not a vowel
4: 'O'
anno@anno-m:~/Documents/mycode/ex10$ ./ex10 helloworld
0: h is not a vowel
1: 'E'
2: l is not a vowel
3: l is not a vowel
4: 'O'
5: w is not a vowel
6: 'O'
7: r is not a vowel
8: l is not a vowel
9: d is not a vowel

实际应用 switch 时

  • 永远要包含一个default:分支,这样就能捕捉到任何之外的输入;
  • 除非真的需要,否则不要在代码里出现“贯穿”,如果出现了,那就添加一个注释//fallthrough,这样其他人就知道这是你特意而为;
  • 永远都要先写好casebreak语句,然后再撰写其中的代码;
  • 如果可以,就用if语句取而代之;

相关文章

网友评论

      本文标题:[习题10]switch

      本文链接:https://www.haomeiwen.com/subject/vsgzgftx.html