M
M
Maxim Markin2013-12-24 15:23:45
.NET
Maxim Markin, 2013-12-24 15:23:45

How does assignment work in C#?

Good day. Have a question, how does assignment work in C#?
There is some code:

for (int i = 1; i < where; i++)
{
     dstr = checkmanyroads(i);
     i = dstr;
}

where checkmanyroads(i) is a function that returns a value. Well, I need to use such a construction, but the program loops / freezes. in Pascal this would pass, but in C# it would not. Any suggestions for an alternative?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mayorovp, 2013-12-25
@owl1n

It would be better not to use the for loop for other purposes, changing the i parameter in the loop body is actually an antipattern. Loops like yours should be written like this:

int i = 1;
while (i < where)
  i = checkmanyroads(i);

PS about Pascal you said in vain. If in C-like languages ​​it is permissible to change the loop counter in its body, although it looks ugly, then in Pascal this is undefined behavior. If you have ever written in Pascal this way, check your programs in Turbo Pascal, Free Pascal and Delphi. I think you will be very surprised.
PPS also has to loop temporarily to put debug output (or learn how to use a debugger). It would be foolish to try to write a two-line loop correctly for a week if the error is in checkmanyroads.

A
Apfel, 2013-12-24
@Apfel

The question is, what does the checkmanyroads(i) function return and why is its value assigned to the iteration variable i ?
According to the code, it turns out that i , overwritten by the value from the function, is infinitely less than where

G
GavriKos, 2013-12-24
@GavriKos

If the return value of checkmanyroads(i) can't be higher than where, then what do you expect? You have i in the loop itself overwritten with a value less than where. So the cycle is endless

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question