Reputation: 84
I want to use ternary operator("? : ") as if statement statement.To be precise I want to do something like this,if(temp>0) so increment 'i' else do nothing.
temp?i++:WHAT_SHOULD_COME_HERE_SO_NO_CHANGES_ARE_MADE_ANYWHERE
Upvotes: 0
Views: 274
Reputation: 73041
This will work:
(void) ((temp>0)?i++:0);
Note that the (void) does not change the behavior of the code; rather it is there to indicate to the reader (and/or any style checking programs you might invoke in the future) that the result of the expression is being deliberately discarded. Without it you may get warnings from the compiler and/or other programmers suspecting a bug and trying to "fix" your code.
Actually, you may get that anyway, since the above is a very unusual way to express what you are trying to do. The code will be easier for others to understand and maintain if you instead use the traditional form:
if (temp>0) i++;
Upvotes: 4
Reputation: 2188
Strictly speaking, you can't do this:
(boolean expression) ? (returning expression) : /* no-op */;
Something has to go in the third operand. However, you can make that "something" behaviorally equivalent to a no-op in terms of the post-conditions of evaluating the ternary operator. See below.
The ternary operator must return a value, and the type is deduced as the most derived type that is a supertype of the return type of each of the second and third operands. So if the third operand is a blank expression (i.e. it returns nothing), then the compiler cannot deduce a return type for the operator as a whole. Thus, it will not compile.
Using the ternary operator:
If you really wanted to, this is how you might do it using the ternary operator:
i = temp>0 ? i+1 : i;
or
temp>0 ? ++i : i;
Preferred syntax:
Although if all you're looking for is a one-liner, then the following syntax is preferred:
if (temp>0) ++i;
Upvotes: 6
Reputation: 3911
you can:
int temp = 20, i = 0;
(temp)? i++: i;
cout << i << endl;
Upvotes: 0
Reputation: 83527
The ternary operator is used in an expression. As such, the entire expression must evaluate to a single value. This means that you must supply both the "if" and "else" clauses. There is no way to leave the "else" part blank.
In addition, embedding an increment operator within an expression such as this is inadvisable since the consequences of the side-effect are so error-prone.
Upvotes: 2