Good examples for ? :

I'm helping a friend to learn C++.
But when it comes to the ?: operator, he's like "what do I need that thing for".

So, I'm looking for some good examples where the ?: really shines.

Anyone?

I don't know if these are 'good' examples, they are a bit contrived, but at least an illustration of possibilities:

1
2
3
4
5
6
    int n = 0;
    
    cout << "Please enter an integer: \n";
    cin  >> n;
    
    cout << "The number is " << (n % 2 ? "odd" : "even") << endl;

When declaring a variable and assigning an initial value. Using if/else you may have to first declare the variable and then assign a different value afterwards:
1
2
3
4
5
6
    string size;

    if (n > 100)
        size = "big";
    else
        size = "small";

It is better to give the initial value when the variable is first declared:
 
    string size = (n > 100) ? "big" : "small";


However it isn't a general-purpose replacement for if/else. It is useful when an expression needs to result in a particular value.
However it isn't a general-purpose replacement for if/else.

Exactly, that's why I'm looking for something nifty.

I've seen a construct once (from Dennis Ritchie btw):

1
2
3
4
void foo(int x){ }
void bar(int x){ }

(call_foo == 1 ? foo : bar)(42);

But I think this is not only a bit too heavy, it also feels kinda evil.
The fundamental difference is that the if-else statement is not an expression, the conditional operator can be used as part of an expression. There are programming situations where only an expression would do; for instance to intialise a constant object.

1
2
3
4
5
6
7
struct A
{
    // an expression is required for direct initialisation of name
    A( const char* cstr ) : name( cstr && *cstr ? cstr : "anonymous" ) {}

    const std::string name;
};
Topic archived. No new replies allowed.