I though it would be nice to learn how to make a code with “?:” in C++ that first increases number, when it reaches 100, it decreases, when it reaches 0, it increases again.
Ok so to clarify: Start number: 1, should write 1 – 100, then at 100, 100, 99, 98, 97 to 0, and so on.
#include <iostream>
using namespace std;
int main () {
int number = 1;
string sign = "plus";
for (int i = 700; i > 0; i--) {
(number==0?sign="plus":(number==100?sign="minus":(sign=="plus"?number++:number--)));
cout << number;
usleep(3000);
}
}
WELL! it sure isnt easy.
(Code above does not work, give error: cannot convert char to int)
THE QUESTION: It doesnt work, how to make it work?
This is not a homework..
Many novice programmers assumes that the ternary operator
?:is just a short-hand if-statement, which is true in many cases (from the novice developers perspective). But there are limitations, and they are not at all the same thing..The evaluated result of the ternary operator has to be the same Type (or convertible to one or the other) no matter if the statement tested is true or false.
In this self-contained example (which fails to compile to easily prove my point) we get the following error;
This is because the expression will evalute to a
std::string&if the statement is true, and anintif it’s false. Two different types depending on which the evaluated expression is true or not? Not allowed.The compiler therefore tries to implicitly convert either side so that a match can be found, but it couldn’t find any suitable conversion and we get the error thrown in our face.
The above snippet will generate a much nicer compile error than we had earlier (when trying to compile it will
g++). And as stated in this post; both result operands of?:needs to be of the same type.