thamu
thamu

Reputation: 29

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

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");

Upvotes: 1

Views: 135

Answers (6)

AnT stands with Russia
AnT stands with Russia

Reputation: 320699

Formally, it can be rewritten as equivalent

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

but there's no meaningful reason to do so, unless it is just a puzzle (or unless there's a credible reason to maintain expression semantics).

Upvotes: 4

user10456568
user10456568

Reputation:

Simplest way, behaving like original, appending nothing if a doesn't match either MACRO1 or MACRO2:

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

Upvotes: -1

Bathsheba
Bathsheba

Reputation: 234845

Setting aside this beautiful answer, this cannot be written as a two "nested" ternary conditional operators since there is nothing to do for any value of a other than MACRO1 and MACRO2, and it's not possible to trick strcpy into a no-op. (The behaviour of copying x to itself is undefined.)

So you are best off leaving the code as it is. Note that in terms of programming history, the ternary conditional operator was invented before the if else control block due perhaps to the deficiencies in the former, as epitomised in the case you present.

You could submit

strnpcy(x, a == MACRO1 ? "S" : "K", 2 * (a == MACRO1 + a == MACRO2));

to the next obfuscation contest though.

Upvotes: 3

0___________
0___________

Reputation: 67835

it can be also

{
    char *dummy;

    dummy = a == MACRO1 ? strcpy(x, "TextA") : a == MACRO2 ? strcpy(x, "TextB") : strcpy(x, "error");
}

Upvotes: -1

bruno
bruno

Reputation: 32596

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 ...

Upvotes: 4

abelenky
abelenky

Reputation: 64730

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

Like your original code, this will copy either "S" or "K" to variable x.

If a is neither MACRO1 nor MACRO2, it will copy "error" to buffer x with an assumption that x is large enough to hold "error" string.
(You should figure out a better way to handle the case where a is neither of the two macros)

Upvotes: 1

Related Questions