forked from daction/Basic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ternary_operator.cpp
70 lines (37 loc) · 878 Bytes
/
ternary_operator.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
//http://www.cplusplus.com/forum/articles/14631/
(x == y) ? a : b
(condition) ? (if_true) : (if_false)
same as
if (condition){
if_true;
}else{
if_false;
}
*/
Example:
if (a >b ){
largest = a;
}else if (b > a){
largest = b;
}else /* a == b */ {
std::cout << "they are the same";
}
That requires 7 lines and is unsuitable for something like a MIN/MAX function:
1) #define MIN(a, b) ((a < b) ? a : b)
2) #define MAX(a, b) ((a > b) ? a : b)
The above code can be used like this:
int largest = MAX(a, b);
largest = ((a > b) ? a : b);
Example:
#include <iostream>
int main() {
int a, b;
a = b = 0;
std::cout << "Enter a number: ";
std::cin >> a;
std::cout << "\nEnter a number: ";
std::cin >> b;
std::cout << "Largest: " << ((a > b) ? a : b) << "\nSmallest: " << ((a < b) ? a : b) << std::endl;
return 0;
}