for (int i = 0; i < X; i++)
myitem = (checkedDB) ? dirtyItem : cleanItem;
I wanted to know if there's a way of flipping checkedDB in the same statement, i.e. the next iteration checkedDB is the opposite of it's value, so like XORing.
for (int i = 0; i < X; i++)
myitem = (checkedDB) ? dirtyItem : cleanItem;
I wanted to know if there's a way of flipping checkedDB in the same statement, i.e. the next iteration checkedDB is the opposite of it's value, so like XORing.
What about:
for (int i = 0; i < X; i++)
myitem = !(checkedDB = !checkedDB) ? dirtyItem : cleanItem;
That may be not really readable/understandable at first sight, but it does what you want in one statement.
One way to toggle a boolean value is bool ^= true
:
for (int i = 0; i < X; i++)
{
myitem = (checkedDB ^= true) ? cleanItem : dirtyItem;
}
I swapped cleanItem
and dirtyItem
since you toggle checkedDB
before one of them is chosen.
The benefit of using checkedDb ^= true
over checkedDB = !checkedDB
is that it is clear that you meant to modify checkedDB
and didn't accidentally mistype a ==
comparison.
Since you haven't specified the language, I can't say for certain if your language will allow an assignment in the conditional part of the ternary operator.
The best answer, IMO, is: not if you have any self-respect. The result will be ugly and confusing, and for no real gain. Here are two distinct solutions that are cleaner and thus easier to understand.
for (int i = 0; i < X; i++)
{
myitem = checkedDB ? dirtyItem : cleanItem;
checkedDB = !checkedDB;
}
The following version doesn't even require the extra variable and achieves your one-line goal:
for (int i = 0; i < X; i++)
{
myitem = i%2 == 0 ? dirtyItem : cleanItem;
}