switch case without break in C language

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/sh

FRUIT="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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值