Nested Inline IF Statements

I'm a little confused as to why this doesn't work:

id = (isChar ? (id + 1 > 122 ? 65 : id++) : id++);


The input here can be either int or char converted to INT. Then I increment id and increment either int or char. The problem is that when I enter char the number doesn't change?


source to share

3 answers

Change id++

to id + 1

in both cases. You are discarding the change from the incremental assignment that is done last.

Generally, avoid side effects (such as ++

) in complex expressions. They make the whole expression insoluble. This brings you here.

Better yet, increment id

in advance, since you always increment it:

id += 1;
if (isChar && id > 122)
    id = 65;



id = (isChar && id > 121) ? 65 : id + 1;




It is extremely bad programming practice that you are using. Conditional expressions shouldn't have side effects; they have to calculate values. You perform a side effect and then discard the side effect! You should either (1) make a side-effect-free version:

id = (isChar && id > 121) ? 65 : id + 1;


or (2) write your version of the side-action as operators, not expressions:

if (isChar && id > 121)
  id = 65;


Let's take a closer look at what's wrong with this simplified version of your original buggy code:

id = whatever ? 65 : id++;


Suppose it whatever

is wrong. What's happening? id++

morally equivalent to:

int PostIncrement(ref int x)
    int temp = x;
    x = temp + 1;
    return temp;


So, suppose you did:

id = whatever ? 65 : PostIncrement(ref id);


What's happening? Let's assume that id

is 1. You pass it by reference PostIncrement

. PostIncrement

makes a copy of the value id

- 1 - in temp

. Then it adds one to that - 2 - and assigns the result id

. So id

now it is 2. Then it returns 1.

Back in the caller, id

it is now 2 and then you assign the result PostIncrement

that was 1 and now id

is 1 again.

Don't use id++

to refer id + 1

to because that's not what it means at all.



Other answers are correct. You should consider their recommendations first, but you can fix this simply by moving the ++ operator in front of the variable, i.e. ++id


Essentially, adding ++ after your variable (postfix increment operation) returns the value of the variable before incrementing. By moving ++ in front of your variable (prefix increment operation), it returns the value of the variable after doing the increment. Note that in both cases, the incremental value is still stored in the variable, which is only affected by the value returned by the operation.

See ++ Operator (C # Reference) for details .



All Articles