Sometimes when looking through a C/C++ codebase you may see these weird symbols littered through code that you do not understand. For example:
z = (x < y) ? 10 : 0;
When I first started coding these operations scared me because I had no idea what was going on at all, but it is more simple than I thought!
The above statement is the same as:
if(x < y) z = 10; else z = 0;
But using the ternary operator cuts the number of lines needed from 4 to 1! Not only does it cut down on the number of lines but it can also increase the readability of a program. Instead of having to look through 4 lines of code (or more if there are more if-else blocks), we can look at one single line with ternary operators. Here is another example:
int sum; int x = 5; int y = 0; sum = (x == 5 ? (y == 0 ? 10 : 5) : 0);
In this case, we are doing a nested ternary operation. The integer sum will be equal to 10 when evaluated. These operations may not look useful but when implementing things like a stretchy buffer (dynamic array in C) these operations help make extremely powerful macros for dealing with dynamic arrays. In my next post, I will go over a super simple dynamic array class in C created with macros, ternary operators, and good ol' pointer arithmetic.