Conditional Operators

Feb 26, 2013 at 7:59pm
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?
Feb 26, 2013 at 8:16pm
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 Feb 26, 2013 at 8:18pm
Feb 26, 2013 at 8:22pm
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 Feb 26, 2013 at 8:22pm
Feb 26, 2013 at 8:27pm
^^^ What he said! ahaha (:
Feb 26, 2013 at 8:28pm
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.
Feb 26, 2013 at 8:35pm
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?
Feb 26, 2013 at 8:36pm
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 Feb 26, 2013 at 8:40pm
Topic archived. No new replies allowed.