if / else statements not symmetric

  • Thread starter Thread starter raylopez99
  • Start date Start date
R

raylopez99

Beware this asymmetric relationship:

statement #1: if (X) {A} else {B}

statement #2: if (!X) {B} else {A}

where X returns a boolean and A,B are statements.

You'll find that it's possible when X changes state from true to false
that A and B will both fire in statement #1, but, in statement #2,
when X changes from false to true, neither B nor A will fire. This
could give problems if you require "A" to do something important in
statement #2, such as to clean up code or initialize it.

Just a quick newbie observation. It really has nothing to do with C#
per se however, just another logical trap like I noted in an earlier
post that logical and boolean operators are not symmetric either (i.e.
A && B != B&&A; A & B != B&A in conditional statements, as the order
of A,B is important).

RL
 
Marc said:

If you're not going to reply, then just don't reply. I wouldn't have seen
this thread at all if it weren't for your reply. Anyone who's inclined to
"FTT" will do so anyway, and they'll get what's coming to them.
 
MC said:
That sounds like a compiler bug, not a logical pitfall. The expression !X is supposed to be evaluated just once. How do you demonstrate that this problem exists, and can you show us the compiled code?

No, the problem is not with the compiler, but with the poster. What he
describes does not happen, he just invents things like this to troll the
newsgroup.
 
Actually I think the code you have in mind is:

#1:  if (X) {A} else if (!X) {B}
#2:  the same

Anything that evaluates X more than once is not correct compilation of the code you originally gave.

Thanks for replying. I took a look at the code I had in mind, and it
was not if/elseif. However, it was a very complex piece of code,
involving evaluating a function that returns a bool [in other words if
(function_returns_bool(x,y,z)) {} else {}].

What I did was make the function return the opposite of what it was
returning, (ie. true instead of false) and the program worked
flawlessly, whereas before it was an infinite loop for the reasons I
gave in the OP.

However, I grant that perhaps this fix was due to some peculiarities
of the function, not the if/else statement, so I will retract my
original statement.

RL
 
However, I grant that perhaps this fix was due to some peculiarities
of the function, not the if/else statement, so I will retract my
original statement.

And the lesson is: before asserting that a language behaves oddly, try
to find a *simple* example which will demonstrate the issue. If you
manage to find a simple example, that's great and it will add weight
to your complaint. If you can't find a simple example, the problem
probably lies in your complicated code.

Jon
 
Back
Top