### Leveraging the Power of Conditional or Ternary Operators

Hi everyone. I'm new to this forum, and fairly new to C++, having gravitated toward it from Java due to some of it's limitations. After making an interesting discovery about ternary or conditional operators, as they are sometimes called, I developed this simple program which demonstrates their power. In some cases, it merely condenses what would otherwise be more extensive if/else statements, but in a few cases they provide even greater efficiency. I've encountered many who know little about them, or comprehend them but don't see the benefits, so I figured this heavily commented example could aid others, particularly beginners, in seeing their potential uses.

 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 /* Conditional/Ternary Operator Madness A simple sample console program with heavy commenting and strategic spacing, designed to demonstrate the potential uses of the conditional or ternary operators. */ //required libraries #include //required for rand function #include //required for cout function #include //required for time function //required to prevent the need for repeated use of 'std::' using namespace std; //global variables using deliberately descriptive names int num,one,two,three,four,five,six,seven,eight,nine,ten; //function to output random numbers within a specific range int random(int low,int high) { return rand()%(high-low+1)+low; } int main() { srand(time(NULL));//set random number seed //loop ten times, generating random number between 1 and 10, //while counting the frequency of each number generated for (int i=1; i<11; i++) { num=random(1,10);//assign variable a random number between 1 and 10 //conditional or ternary operator used to increment correct variable ((num==1) ? one : (num==2) ? two : (num==3) ? three : (num==4) ? four : (num==5) ? five : (num==6) ? six : (num==7) ? seven : (num==8) ? eight: (num==9) ? nine : ten)++; //conditional or ternary operator used to add spacing //when the number of iterations is even cout<<((i%2) ? "" : "\t"); cout<
Last edited on
Topic archived. No new replies allowed.