Click to See Complete Forum and Search --> : Conditional operator inside function calls


RRam_k
June 25th, 2002, 12:15 AM
Hi NG,
I am using conditional operators extensively in my program for just to avoid simple if and else conditions.Please see the code below

#include "stdafx.h"
#include <conio.h>

void check(BOOL flag,int x)
{
printf("Result is %d,%d",flag,x);

}


int main(int argc, char* argv[])
{

int a=10,b=20;
BOOL x=TRUE,y=FALSE;
if(x==TRUE)
{
if(b>a)
check(FALSE,b);
else
check(FALSE,a);
}
else
{
if(b>a)
check(TRUE,b);
else
check(TRUE,a);
}


//check((x==TRUE) ?FALSE:TRUE,(b>a)?b:a); //uncomment this code and comment the if and else
getch();
return 0;
}

I want to know the pros and cons of using the conditional operator inside a function call. Is the code is efficient or inefficient? Is it conforms to the standard code writing practice? I have just looked into the assembly code generated for the both. The code generated for the function call with conditional operator is around 15 and the other one is around 29.

Thanks in Advance
with kind regards
Raghuram

cup
June 25th, 2002, 12:28 AM
Using the conditional triadic operator is not really more efficient. It is just that the if-then-else version has 4 calls to check whereas the conditional triadic operator version only has one call.
At the end of the day, it is just a space/readability/maintenance issue.

If you are short of space on a ROM, then the less code you generate the better. Even changing loop counters to ints reduces the amount of generated code.

Some people just cannot understand the triadic operator (see Obfuscated Programming Contest - loads there). Others do not find it a problem. There are also in-house standards where most companies specify that you should not nest the triadics.

Some people are nervous about boolean assignments, so you will see totally unnecessary coding. eg

x = y == z ? true: false

This can be replaced by

x = y == z

jfaust
June 25th, 2002, 10:45 AM
An alternative to both:


int main(int argc, char* argv[])
{
int a=10,b=20;
BOOL x=TRUE,y=FALSE;

check(!x, std::max(a, b));

getch();
return 0;
}


I know it was just an example. The point is that unless you have unique constraints, the most important aspect is maintainability. If you are woried about size, you can probably get by by making less function calls, as in my example.

Jeff