switch case without break in C language

来源:互联网 发布:如何查到淘宝客佣金 编辑:程序博客网 时间:2024/04/29 03:37

In C switch case senario, if you not using break key word, pay attention the control flow!


Code example(net/bridge/br_input.c in linux kernel)

forward:

    switch (p->state) {
    case BR_STATE_FORWARDING:  //[1]
        rhook = rcu_dereference(br_should_route_hook);
        if (rhook != NULL) {
            if (rhook(skb))
                return skb;
            dest = eth_hdr(skb)->h_dest;
        }
        /* fall through */   <==========  the above case without break !!!
    case BR_STATE_LEARNING:  //[2]
        if (!compare_ether_addr(p->br->dev->dev_addr, dest))
            skb->pkt_type = PACKET_HOST;
    
        NF_HOOK(PF_BRIDGE, NF_BR_PRE_ROUTING, skb, skb->dev, NULL,
            br_handle_frame_finish);
        break;
    default:
drop:
        kfree_skb(skb);
    }
    return NULL;


So above piece of code will following below control flow:

when p->state == BR_STATE_LEARNING, the code will skip [1] and only execute [2],

when p->state == BR_STATE_FORWARDING, the code will first go [1], then will continue execute [2], no need judge condition "p->state == BR_STATE_LEARNING" again.

Finally summary the function br_handle_frame_finish will be called either p->state == BR_STATE_LEARNING or when p->state == BR_STATE_FORWARDING.


In shell language, there is no break key word, but it's behavior like exist break.

Following example will show if apple match, the case will break out immediately, means output will be

"Apple pie is quite tasty."

#!/bin/shFRUIT="apple"case "$FRUIT" in   "apple") echo "Apple pie is quite tasty."    ;;   "banana") echo "I like banana nut bread."    ;;   "kiwi") echo "New Zealand is famous for kiwi."    ;;esac


0 0
原创粉丝点击