Home > Software engineering >  Compact if statement C
Compact if statement C

Time:02-04

I just would like to be sure that I can write a compact if with a or condition in the following way:

const ST c_is = ((kg==0) || (kg==nktot)) ? 0 : 10;

The purpose is to set c_is to 0 if kg is 0 or nktot and 10 otherwise.

Could you confirm me that it is ok?

CodePudding user response:

The purpose is to set c_is to 0 if kg is 0 or nktot and 10 otherwise.

Could you confirm me that it is ok?

It is ok.

CodePudding user response:

Yes, it's ok.

From the most readable to the most obscure:

// give more meaningful names, as it is only you know what these ids mean
constexpr ST set_is(ST kg) 
{
    if (kg == 0 || kg == nktot)
        return 0;
    return 10;
}

constexpr ST c_is = set_is(kg);
constexpr ST c_is = ((kg==0) || (kg==nktot)) ? 0 : 10;
constexpr ST c_is = [=] {
    if (kg == 0 || kg == nktot)
        return 0;
    return 10;
}();
constexpr ST c_is = (kg !=0 && kg !=nktot) * 10;
  •  Tags:  
  • Related