Optimize ternary operator

后端 未结 6 1978
野的像风
野的像风 2021-02-03 18:49

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is th

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 19:49

    What an ugly mess. I broke it out into if and else's just to see what it was doing. Not much more readable, but thought I'd post it anyways. Hopefully someone else has a more elegant solution for you. But to answer your question, don't use ternaries that complicated. No one wants to do what I just did to figure out what it's doing.

    if ( req.security_violation )
    {
        if ( dis_prot_viol_rsp && is_mstr )
        {
            exp_rsp_status = uvc_pkg::MRSP_OKAY;
        }
        else
        {
            exp_rsp_status = uvc_pkg::MRSP_PROTVIOL;
        }
    }
    else if ( req.slv_req.size() )
    {
        if ( ( is_mst_abort_rsp && dis_mst_abort_rsp ||
             ( req.slv_req[0].get_rsp_status() == uvc_pkg::MRSP_PROTVIOL && dis_prot_viol_rsp ) ||
             ( is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp ) )
        {
            exp_rsp_status = uvc_pkg::MRSP_OKAY;
        }
        else
        {
            exp_rsp_status = req.slv_req[0].get_rsp_status();
        }
    
    }
    else
    {
        exp_rsp_status = uvc_pkg::MRSP_OKAY
    } 
    

提交回复
热议问题