Here is my observation while I was analyzing a big code base. Here is the code pushed by developer for review
/*comparing received RAT Type from ip packet with numeric value */
if(pDefBearer.data.recv.ratType == 1)
{
avp.my_ccr.rattype = GERAN; /* setting RAT as GERAN(enumerated value) i.e 2G */
/* further processing of packet */
}
else
{
avp.my_ccr.rattype = UTRAN;
}
And this was the code reviewer comments
As a coding guidelines, we can always use macro and numbers on the left side in the
if()check. This help us to give compilation error, whenever we wrongly use=instead of==
And it got resolved as
if(pDefBearer.data.recv.ratType == DB_RAT_GERAN) /* DB_RAT_GERAN is a macro defined somewhere in header file */
{
avp.my_ccr.rattype = GERAN; /* setting RAT as GERAN i.e 2G */
/* further processing of packet */
}
else
{
avp.my_ccr.rattype = UTRAN;
}
which is correct as sometime one may mistakenly use = instead of == like
if(pDefBearer.data.recv.ratType = 1) { /* always set RAT as 2G */ }
and compiler won't produce any warning(Good compiler, may be yes but hardly anyone analyze make or build result until it got crashed) or error about the same & it creates a problem.
Now here I got curios, one can use like
if(DB_RAT_GERAN == pDefaultBearer.data.recv.ratType)
rather than
if(pDefaultBearer.data.recv.ratType == DB_RAT_GERAN)
I prefer to use MACRO on Left hand side of comparison operator rather than Right hand side, as in worst case if mistakenly = is used in place of == like below
if(DB_RAT_GERAN = pDefaultBearer.data.recv.ratType){ }
compiler produces a very meaningful error like
error: lvalue required as left operand of assignment
but this
if(pDefaultBearer.data.recv.ratType = DB_RAT_GERAN) { }
simply get away.
Which of above two is advisable to use or even better technique & does anything C standard says about the same i.e MACRO should be used on LHS of comparison operator in checks or on RHS side ?
Aucun commentaire:
Enregistrer un commentaire