简体   繁体   中英

Why doesn't the increment operator (++/--) work while using the ternary if/else operators?

Similar to the bellow question, however I'm expanding with more specific inquiries. Also, this is setting aside opinions on whether or not to use the ternary or normal styling of if/else's. Applying increment using ternary operator in Java

So in theory, the following snippet:

if (text.equals("foo"))
    data++;
else if (text.equals("bar"))
    data--;

should look like this using the ternary operators:

data = text.equals("foo") ? data++ : text.equals("bar") ? data-- : data;

However, in my android (Java) application, android studio showed me a warning:

The value changed at 'data++' is never used

Like-wise, when I ran this in my application, the data variable stayed the same. However, when I changed the line of code to this:

data = text.equals("foo") ? data + 1 : text.equals("bar") ? data - 1 : data;

It worked.

So, this makes me wonder if the ++/-- operator is allowed within this context? Does anyone have any input on this?

The post-increment ( data++ ) and post-decrement ( data-- ) operators return the value of the variable prior to its increment/decrement, so assigning it back to the variable cancels the increment/decrement.

You can use pre-increment and pre-decrement instead (or data + 1 and data - 1 as you did):

data = text.equals("foo") ? ++data : text.equals("bar") ? --data : data;

因为它仅检查条件并在条件为真或假时返回答案,所以如果您真的想应用增量减量,则它不能与增量减量运算符一起使用,因为您可以应用循环,并且在这种情况下,如果计数增量则放在计数操作上然后执行递增操作,否则执行递减操作

In ternary operators, if you break it down, it will be

if(text.equals("foo")){
data = data++;
} else if(text.equals("bar")){
data = data--;
} else {
data = data;
}

And you are using post incremental and decremental operator on variable, which is assigned to itself. This can be break as

data = data++; This can be seen as 
int temp = data; 
data = data +1;
data = temp;

And same with the post incremental case. So in every case data value will not change. With example

data = 10;
int temp = data;// temp = 10;
data = data + 1; // data = 11;
data = temp; // data = 10;

you can also remove the assignment from the statement and it will works fine. ie

text.equals("foo") ? data++ : text.equals("bar") ? data-- : data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM