163

I was converting a C++ algorithm to C#. I came across this for loop:

for (u = b.size(), v = b.back(); u--; v = p[v]) 
b[u] = v;

It gives no error in C++, but it does in C# (cannot convert int to bool). I really can't figure out this for loop, where is the condition?

Can someone please explain?

PS. Just to check, to adapt a VECTOR to a LIST does b.back() correspond to b[b.Count-1] ?

24
  • 38
    Where is the condition? That would be u--. The semi-colons are used to delimit the various parts of the for statement. Jul 31, 2012 at 11:20
  • 80
    This is quite a normal loop. C# doesn't convert numbers to bools implicitly so you need to turn the condition into ; u-- != 0; Jul 31, 2012 at 11:21
  • 29
    @Jessie Good--Good code has nothing to do with what is allowable in the language, it has to do with how long it takes an unacquanted co-worker to read the code. If it causes any kind of confusion, it's not the best possible solution, even if it's legal. Often a more verbose solution is Much better than a terse one, and most compilers will compile to the same thing either way.
    – Bill K
    Jul 31, 2012 at 19:57
  • 18
    I hope that, after converting the code, you give the variables better names than b, u, v, etc. The only reason they were named this way is because someone wanted to look smart by making their code unreadable.
    – Dan
    Jul 31, 2012 at 20:39
  • 33
    @houbysoft: this is a general stackoverflow problem. If you ask a very detailed, well researched and interesting question in a specific research domain, which leads to a solution to a hard and interesting problem, and you answer such a question after a hard days worth of research, you will get only a few dozen visitors and one or two upvotes from a few experts in the field. If you want to gain a lot of rep quickly, you have to ask and answer questions like these. "How do I add two numbers in php", "what does do mean in C++" - will get thousands of hits from beginners looking for a tutorial.
    – vsz
    Aug 1, 2012 at 3:20

12 Answers 12

321

The condition of the for loop is in the middle - between the two semicolons ;.

In C++ it is OK to put almost any expression as a condition: anything that evaluates to zero means false; non-zero means true.

In your case, the condition is u--: when you convert to C#, simply add != 0:

for (u = b.size(), v = b.back(); u-- != 0; v = p[v]) 
    b[u] = v; //                     ^^^^ HERE
4
  • 55
    By the way, Thomas may have been confused by the use of the comma too, it's very different than the semi-colon, it lets you do multiple things in one section of the for loop (in this case, it initialized two variables). Last time I checked these unusual constructs weren't considered the most readable solution possible and may therefore be frowned-upon by some.
    – Bill K
    Jul 31, 2012 at 19:50
  • 2
    If I remember correctly, and expression containing a comma has the value of the last subexpression on the right. This comes from C and can be used in any expression, not only in a for loop.
    – Giorgio
    Aug 1, 2012 at 8:04
  • 7
    @Roger This wouldn't be the same loop since you are decrementing u at the end of the loop, instead of the beginning (i.e. after b[u] = v instead of before). In fact you would need to initialize it with u = b.size() - 1 instead.
    – Didier L
    Aug 1, 2012 at 13:07
  • Fyi: I just pushed you over the 500K limit. Is that like being the one millionth customer somewhere and winning somethin? In any case: many congratulations; always looking up to your precise, sharp answers! Keep going; meet you making the 1 million thing ... later this century.
    – GhostCat
    May 11, 2017 at 10:32
166

Lots of accurate answers, but I think it's worth writing out the equivalent while loop.

for (u = b.size(), v = b.back(); u--; v = p[v]) 
   b[u] = v;

Is equivalent to:

u = b.size();
v = b.back();
while(u--) {
   b[u] = v;
   v = p[v];
}

You might consider refactoring to the while() format as you translate to C#. In my opinion it is clearer, less of a trap for new programmers, and equally efficient.

As others have pointed out -- but to make my answer complete -- to make it work in C# you would need to change while(u--) to while(u-- != 0).

... or while(u-- >0) just in case u starts off negative. (OK, b.size() will never be negative -- but consider a general case where perhaps something else initialised u).

Or, to make it even clearer:

u = b.size();
v = b.back();
while(u>0) {
   u--;
   b[u] = v;
   v = p[v];
}

It's better to be clear than to be terse.

19
  • 29
    This answer not only clarifies the bad code but also gives a good alternative. 1 up!!
    – polvoazul
    Jul 31, 2012 at 17:25
  • 2
    As an aside, I'd be careful with the while (u-- >0) form. If the spacing gets messed up, you might end up with a "down to zero" loop: while (u --> 0), which tends to confuse everyone at first glance. (I'm not sure if it's valid C#, but it is in C, and I think it may be as well in C++?)
    – Izkata
    Jul 31, 2012 at 18:09
  • 9
    I don't think your code is necessarily clearer. The point of for instead of while is precisely that you put the initialization and the increment/decrement in one statement, and that doesn't necessarily make the code harder to understand. Otherwise, we shouldn't be using for at all.
    – musiphil
    Jul 31, 2012 at 22:11
  • 1
    It's also important to rewrite as little code as possible. (The for loop could change, after all.) You've put "u--" in two separate places, and the loop isn't really clearer (I can see what the for loop does in one glance; I have to scan with multiple lines). Being terse has benefits too. Don't downplay them. Still though, a good example of how else it could be written. It does make it easier to understand for anyone who's not used to for statements in C++ (or maybe even at all).
    – NotKyon
    Aug 1, 2012 at 6:15
  • 2
    @Izkata: It isn't EVER an operator, it's parsed as a -- token followed by a > token. Two separate operators. A "down to zero" loop is just a straightforward combination of post-decrement and greater-than. C++ operator overloading doesn't create new operators, it just repurposes existing ones.
    – Ben Voigt
    Aug 2, 2012 at 16:07
66

The condition is u--;, because it is in the second position of the for instruction.

If the value of u--; is different from 0, it will be interpreted as true (i.e., implicitly casted to the boolean value true). If, instead, its value is 0, it will be casted to false.

This is very bad code.

Update: I discussed the writing of "for" loops in this blog post. Its recommendations can be summarized in the following paragraphs:

A for loop is a practical, readable (once you get used to it) and terse construct, but you need to use it well. Because of its uncommon syntax, using it in a too imaginative way is not a good idea.

All parts of the for loop should be short and readable. Variable names should be chosen to make it easy to understand.

This example clearly violates these recomendations.

18
  • 3
    Or it will stop at u == 0 probably...?
    – Thomas
    Jul 31, 2012 at 11:24
  • 2
    No; in C++ there's an implicit conversion from int to bool, with 0 converting to false. The loop will terminate when u-- == 0. In C#, there's no such implicit conversion so you'd have to explicitly say u-- == 0. EDIT: This is in response to your first comment.
    – Chris
    Jul 31, 2012 at 11:25
  • 49
    This is terrible code, for one very simple reason; you could not easily comprehend it when you read it. It's "clever", a "hack"; it makes use of a combination of coding structures, and knowledge of how they work behind the scenes, to create a structure that does the job but that defies understanding, because it's not in the form that the language authors envisioned and that was communicated to most language users.
    – KeithS
    Jul 31, 2012 at 15:47
  • 4
    Excellent answer. I'd +1 it... if not the "This is very bad code." statement ;)
    – Sandman4
    Jul 31, 2012 at 16:07
  • 14
    I don't understand why so many people seem to think u-- is really bad code simply because of the missing (implicit in C++) != 0. Surely anyone working with code will be perfectly aware that 0=false, every other value=true. There's far more scope for confusion regarding pre-/post-incrementing of u, or people perhaps assuming that u = b.size() will always execute before v = b.back() (my understanding is the execution sequence there is undefined, but I stand to be corrected). Jul 31, 2012 at 20:36
23

This will be the C# form of your loop.

// back fetches the last element of vector in c++.
for (u = b.size(), v = b.back(); (u--) != 0; v = p[v]) 
{      
  b[u] = v;      
}

Just replace equivalent for size() and back().

What it does is reverses the list and stores in an array. But in C# we directly have system defined function for this. So you don't need to write this loop also.

b = b.Reverse().ToArray();
8
  • 1
    by taking v = b.back(); out of the for intializer didn't you just change the way it works, since the v = p[v] is overridden by Jul 31, 2012 at 15:01
  • v = p[v] will not have any effect on final result as this line will execute at the last. And after that v is not referred in the loop. This line is there just to show how the loop is converted from c++ to C#.
    – Narendra
    Jul 31, 2012 at 15:08
  • 1
    in the c++ code v = b.back(); was executed once before the iterations started and v = p[v] was executed at the beginning of each iteration. In that C# version v = p[v] is still executed at the beginning of each iteration but v = b.back(); is executed right after it, changing the value of v for the next instruction b[u] = v;. (maybe the question was edited after you read it) Jul 31, 2012 at 15:21
  • 5
    @Rain The issue is v = b.back(). You have it executing at every loop iteration instead of just the first one - we don't know what back() does (are there any side-effects? Does it change the internal representation of b?), so this loop is not equivalent to the one in the question.
    – Izkata
    Jul 31, 2012 at 15:22
  • 1
    @Rain Exactly, take a closer look at it yourself. The initialization step happens only once before the loop begins, not at the beginning of every iteration. Your code would be correct if v = b.back() was moved outside the loop, above it. (Also, if you're trying to respond to someone, use @ in front of their name, so we get a notification)
    – Izkata
    Jul 31, 2012 at 18:07
15
u = b.size(), v = b.back()

is initialization.

u--

is the condition.

v = p[v]

is the iteration

14

The condition is the result of u--, which is the value of u before it was decremented.

In C and C++, an int is convertible to bool by implicitly doing a != 0 comparison (0 is false, everything else is true).

b.back() is the last element in a container, which is b[b.size() - 1], when size() != 0.

11

In C everything non-zero is true in "boolean" contexts, such as the loop end condition or a conditional statement. In C# you have to make that check explicit: u-- != 0.

1
  • This is not the question of OP. He is asking about the evaluation of the terminal condition (i.e. 'u--' in this case).
    – ApplePie
    Jul 31, 2012 at 11:21
6

As stated by others, the fact that C++ has implicit casting to boolean means the conditional is u--, which will be true if the value is non-zero.

It's worth adding, that you've a false assumption in asking "where's the conditional". In both C++ and C# (and other similarly syntaxed languages) you can have an empty conditional. In this case it always evaluates to true, so the loop continues forever, or until some other condition exits it (via return, break, or throw).

for(int i = 0; ; ++i)
  doThisForever(i);

Indeed, any part of the for statement can be left out, in which case it's just not performed.

In general, for(A; B; C){D} or for(A; B; C)D; becomes:

{A}
loopBack:
if(!(B))
  goto escapeLoop;
{D}
{C}
goto loopBack;
escapeLoop:

Any one or more of A, B, C or D can be left out.

As a result of this, some favour for(;;) for infinite loops. I do because while while(true) is more popular, I read that as "until truth ends being true", which sounds somewhat apocalyptic compared to my reading for(;;) as "forever".

It's a matter of taste, but since I'm not the only person in the world to like for(;;) it's worth knowing what it means.

4

all the answers are correct :-

for loop can be used in a variety of ways as follows :

Single Statement inside For Loop
Multiple Statements inside For Loop
No Statement inside For Loop
Semicolon at the end of For Loop
Multiple Initialization Statement inside For
Missing Initialization in For Loop
Missing Increment/Decrement Statement
Infinite For Loop
Condition with no Conditional Operator.
4
for (u = b.size(), v = b.back(); u--; v = p[v]) 
   b[u] = v;

In above code, u and v are initialized with b.size() and b.back().

Every time the condition is checked, it executes decrement statement too i.e. u--.

The for loop will exit when u will become 0.

3

The error encountered in C# itself clears the doubt. The for-loop searches for a

FALSE

condition to terminate. And as we know,

(BOOL) FALSE = (int) 0

but C# cannot process this on its own unlike as C++. So the condition you are searching for is

u--

but you have to explicitly give the condition in C# as

u-- != 0

or

u-- > 0

But still try to avoid this kind of coding practice. The

while loop

stated above in answer is one of the most simplified version of your

for-loop.

1
  • @Downvoter: Downvoting is alright as far as you ain't satisfied by the solution but at the same time, please take time to state the reason, so that the answers could be improved.
    – Abhineet
    Mar 11, 2013 at 7:41
3

If you're used to C / C++ this code isn't so hard to read, though it's pretty terse and not that great of code. So let me explain the parts that are more Cism than anything else. First off the general syntax of a C for loop looks like this:

for (<initialization> ; <condition>; <increment>)
{
    <code...>
}

The initialization code gets run once. Then the condition gets tested before every loop and lastly the increment gets called after every loop. So in your example you'll find the condition is u--

Why does u-- work as a condition in C and not C#? Because C implicitly converts a lot of things too bools and it can cause trouble. For a number anything that is non-zero is true and zero is false. So it will count down from b.size()-1 to 0. Having the side-effect in the condition is a bit annoying and it would be preferable to put it in the increment part of the for loop, though a lot of C code does this. If I were writing it I would do it more like this:

for (u = b.size() - 1, v = b.back(); u>=0; --u) 
{
    b[u] = v;
    v = p[v]
}

The reason for this is, to me at least, it's clearer. Each part of the for loop does it's job and nothing else. In the original code the condition was modifying the variable. The increment part was doing something that should be in the code block etc.

The comma operator may be throwing you for a loop also. In C something like x=1,y=2 looks like one statement as far as the compiler is concerned and fits into the initialization code. It just evaluates each of the parts and returns the value of the last one. So for example:

std::cout << "(1,2)=" << (1,2) << std::endl;

would print out 2.

1
  • The problem with your rewrite is that if b.size() is unsigned, it will iterate for a very long time. (Also, you're missing a semicolon.) But at least you didn't take the "'Dick and Jane' is good English" approach that so many of the other answers and comments did, lauding absurdly verbose rewrites that are only easier to read by neophytes and other unskilled programmers.
    – Jim Balter
    Sep 24, 2012 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.