How this if-else condition can be replaced by ternary operator

  • A+
Category:Languages

Please help me to rewrite the below condition in a better way

This is a c code

 if(a == MACRO1)  strcpy(x,"S") else if (a == MACRO2)  strcpy(x,"K"); 

 


if(a == MACRO1)  strcpy(x,"S") else   strcpy(x,"K"); 

can be :

strcpy(x, (a == MACRO1) ? "S" : "K"); 

but

if(a == MACRO1)  strcpy(x,"S") else if (a == MACRO2)  strcpy(x,"K"); 

has a missing else and to do

strcpy(x, (a == MACRO1) ? "S" : ((a == MACRO2) ? "K" : x)); 

is not correct because the argument of strcpy must not overlap but in that specific case not sure it is a true problem (even undefined behavior) , but also x is may be not yet initialized, and what about the performances ...

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: