Determine if a variable is less than 0 without if statement [closed]

There seems to be a fundamental misunderstanding.

if itself does not perform any comparison; it just runs a branch or the other depending from the value of a boolean expression, e.g. x<0. Now, since C++ is rich of other conditional constructs and can use a boolean expression as an index, you can always exploit the expression that actually does the comparison in many ways:

switch(x<0)
{
    case true:
        std::cout<<"x < 0\n";
        break;
    default:
        std::cout<<"x >= 0\n";
}

std::cout<<(x<0?"x < 0":"x >= 0")<<"\n";

const char *sign[]={">=", "<"};
std::cout<<"x "<<sign[x<0]<<" 0\n";

x<0 && puts("x<0");
x<0 || puts("x>=0");

while(x<0)
{
    std::cout<<"x<0\n";
    break;
}
while(!(x<0))
{
    std::cout<<"x>=0\n";
    break;
}

/* ... */

void l() { puts("x<0");}
void g() { puts("x>=0");}

/* ... */

void (*fns[])={g, l};
fns[x<0]();

/* ... */
struct B {
    virtual void doIt()=0;
}

struct D1 : B {
    void doIt() { std::cout<<"x<0\n"; }
}

struct D2 : B {
    void doIt() { std::cout<<"x>=0\n"; }
}

D2 d2; D1 d1;
B *arr[] = {&d2, &d1};
arr[x<0]->doIt();

Leave a Comment