I have a following code:
#include <iostream>
int main() {
int i = 3;
do {
(i == 3) ? (std::cout << "Is 3.\n") : ++i;
++i;
} while ( i < 4 );
return 0;
}
And got a following error in response:
ternary.cc: In function ‘int main()’:
ternary.cc:5:43: error: invalid conversion from ‘void*’ to ‘int’ [-fpermissive]
What is wrong with my code?
You’re abusing the ternary operator a bit, for any given
a ? b : cI would expect the result to be stored somewhere and I wouldn’t recommendborchaving side effects.The root of your problem is that the ternary operator requires
bandcto be the same/equivalent type. Andrew’s explanation that they need to be able to “resolve to the same … type” is probably more accurate.For what it’s worth, you can use a sleight-of-hand (or even more abuse, depending on your perspective) to make the code work:
Or, more explicitly, make sure both are the same type: