the Ternary operator

Can someone teach me how ternary operator works i really cant understand it. Thanks
In short, [cond]?[then]:[else] equals to
1
2
3
4
5
6
7
8
[return type] ternary()
{ 
    if([cond]) {
        return [then]
    } else {
        return [else]
    }
}


Main difference between if construction and ternary operator is that ternary operator returns value, so you can do things like:
1
2
3
int n;
std::cin >> n;
n = (n > 0?10:-10);
This sets n to 10 if user input positive value and -10 otherwise
Last edited on
n = (n > 0:10:-10); shouldn't this be n = n > 0 ? 10 : -10;
Whoops, typo. Thanks for noticing. Fixing it.
Topic archived. No new replies allowed.