What is the benefit of terminating if … else if constructs with an else clause?

前端 未结 12 1026
不思量自难忘°
不思量自难忘° 2020-11-27 13:37

Our organization has a required coding rule (without any explanation) that:

if … else if constructs should be terminated with an el

12条回答
  •  醉梦人生
    2020-11-27 13:59

    Well, my example involves undefined behavior, but sometimes some people try to be fancy and fails hard, take a look:

    int a = 0;
    bool b = true;
    uint8_t* bPtr = (uint8_t*)&b;
    *bPtr = 0xCC;
    if(b == true)
    {
        a += 3;
    }
    else if(b == false)
    {
        a += 5;
    }
    else
    {
        exit(3);
    }
    

    You probably would never expect to have bool which is not true nor false, however it may happen. Personally I believe this is problem caused by person who decides to do something fancy, but additional else statement can prevent any further issues.

提交回复
热议问题