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?
1
2
3
4
5
6
7
8
9
10
11
12
13
// Conditional operator

#include <iostream>

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:
1
2
3
4
5
6
7
8
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Conditional operator

#include <iostream>
#include <string>

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.