The correct Ternary protocol format

This is what I have. I'm not sure how to write it right. I tried Googling, but to no avail. Please do not cringe too much:

cout << (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n" : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n" : ""; 

What I need to do is:

  // Gives hint that inputted number is higher or lower // than inputted number if (guess > randomNumber) cout << "\nWhoops! Try again!" << " You guessed higher than the random number!\n" << endl; else if (guess < randomNumber) cout << "\nWhoops! Try again!" << " You guessed lower than the random number!\n" << endl; 

Any help would be greatly appreciated. I just want to learn how I can write my programs in order to be more efficient and smaller. Thank you for your feedback.

+6
source share
2 answers

Put some brackets around the whole expression, otherwise you will end up printing boolean values:

 int guess = 10; int randomNumber = 9; cout << (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n" : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n" : "" ; // Output: 1 

The correct code is:

 int guess = 10; int randomNumber = 9; cout << ( (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n" : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n" : "" ); // Notice the brackets! /*Output: Whoops! Try again! You guessed higher than the random number!*/ 
+4
source

more efficient

It is not related to what you do there (if by "effective" you mean the best characteristics of the execution time).

less

A humble goal, but not if, due to it, readability does not match (and even more so if, due to the syntactic complexity ... missing brackets ... the end result is incorrect).

Remember: code is written for people to read.

You should probably follow the if and else approach, which you also show in the question. However, IMHO the “good” approach (if you really need to ignore this) is to pack it into some function:

 template<class T, class X, class Y, class Z> void comp_if(T value, T reference, X less, Y equal, Z greater) { if (value < reference) less(); else if (value > reference) greater(); else equal(); } 

Used as

 // missing real macros a lot comp_if(foo, bar, []() {cout << "less"; }, []() {cout << "equal";}, []() {cout << "greater"}); 

Whether this really helps with readability is the choice that I leave to the reader.

+1
source

All Articles