for the following:
( a != b ) ? cout<<"not equal" : cout<<"equal";
suppose I don't care if it's equal, how can I use the above statement by substituting cout<<"equal"
with a no-op.
for the following:
( a != b ) ? cout<<"not equal" : cout<<"equal";
suppose I don't care if it's equal, how can I use the above statement by substituting cout<<"equal"
with a no-op.
This is very confusing code. You could just write
cond ? cout << "equal" : cout;
but you won't (will you?) because you've got conventional if
for that.
If it really is for a ternary operator that doesn't need a second action, the best option would be to replace it for an if:
if (a!=b) cout << "not equal";
it will smell a lot less.
Simple: I would code it as
if (a != b)
cout << "not equal";
The ternary operator requires the two results to be of the same type. So you might also be able to get away with
(a != b) ? cout << "not equal" : cout;
because the stream operator (<<) just returns the ostream reference. That's ugly and unnecessary in my opinion though.
I think the problem here is that the operator : has two EXPRESSIONS as arguments. Let's say.. a = x ? y : z;
Expression by definition must have a value...that's why you cannot just "skip".
The only thing missing from the other answers is this: There is no way, directly, to code a "noop" in C/C++.
Also, doing: (a != b) ? : printf("equal\n");
does actually compile for me (gcc -ansi in gcc 4.2.4).
The syntax just requires a expression. You can just go: (a!=b)?cout<<"not equal":1;
The following will achieve what you're looking for, however, it may not be clear to people reading your code why it works:
(a != b) && (cout << "equal");
Personally, I agree with this answer from Vinko Vrsalovic.
If the focus of the code is the output operation and not the condition, then something like this could be done:
cout << (cond ? "not equal" : "");
I suspect that's not the case, though, because you want to do nothing in the "else" clause.