### Conditional Operators

I have read several articles and visited several websites trying to grasp the concept of the conditional operator but I cant seem to grasp it, can someone explain it to me? How it functions?
 ``12345678910111213`` ``````// Conditional operator #include int main() { int i = 7; int j = 5; std::cout << ( i > j ? i : j ) << " is greater than " << ( i > j ? j : i ) << '\n'; return 0; }``````

This will 'cout' the highest number, then the lowest.

Note how I have switched the second conditional statement at the end.
From `i : j` to `j : i`

`( i > j ? i : j )`

`i > j` - If i is greater than j
`i else j`

If the first part is true, use the left side, else, use the right side.

Hope you can understand that. (:
Last edited on
This:
`condition ? action1 : action2;`

is actually the simplified version of:
 ``12345678`` ``````if ( condition ) { action1; } else { action2; }``````

Hope that helps.
Last edited on
^^^ What he said! ahaha (:
 I have read several articles and visited several websites
After all that, I reckon the best way to learn is to stop reading about it, and start trying it out for yourself. Get a compiler, write a few lines of code and see what happens.
Ohhhhh!!!! I got it! :) So whatever comes AFTER the colon separator is the "else"? So like if the condition is true, print the first number, if the condition is false, print the number after the colon?
Yes. I've never actually used this until I read your post! aha.

I just coded this:
 ``123456789101112131415161718192021222324252627282930313233343536`` ``````// Conditional operator #include #include bool searchFunction( const std::string &name ) { const int nameTotals = 3; std::string names[ nameTotals ] = { "Dave", "Steve", "Pete" }; for( int idx = 0; idx < nameTotals; ++idx ) if( name == names[ idx ] ) return true; return false; } int main() { std::string name; std::cout << "Enter a username: "; std::getline( std::cin, name, '\n' ); bool correctUsername; searchFunction( name ) ? correctUsername = true : correctUsername = false; correctUsername ? std::cout << "Username found.\n" : std::cout << "Username not found!\n"; return 0; }``````
Last edited on
Topic archived. No new replies allowed.