Jump to content

C# problem

- - - - -

  • Please log in to reply
3 replies to this topic

#1
dcord

dcord

    Newbie

  • Members
  • PipPip
  • 25 posts
how do you would remove any BREAK statement from a loop and replace it with a structured equivalant.

#2
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
that depends on the loop. Can you provide an example?

I'll show you a possible example:


while (i < 10) {

    if (i == 2) {

        break;

    }

    i = rnd.Next(1, 10);

}


could be replaced with

while (i < 10 && i != 2) {

    i = rnd.Next(1, 10);

}


there are times, when breaks can make things more readable, or less readable.

Any time you feel you need to use one, I'd challenge you to think about it. But if you had a good enough reason, I'd drop it.

goto's are my big issue.. =)

#3
dcord

dcord

    Newbie

  • Members
  • PipPip
  • 25 posts
Thanks for you reply.

so in essence you are using conditional operators to replace the break correct?
Also do you use the same method to remove breaks from different types of loops?

#4
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
Yup, normally.

I've seen things like this a few times over the years

string input;

while (true) {

     input = Console.ReadLine();

     if (input == "quit")

          break;

}


could just as easily be replaces with something like this

string input;

do {

     input = Console.ReadLine();

} while (input != "quit");


but it's not always breaks I'm concerned about. And sometimes breaks can make something more readable. But I wont go into that right now,

but just for the sake of discussion, there's a whole world of elegance to loops. have you ever seen a for loop used to iterate something that isn't indexed?
example on an array:

for (int i = 0; i < array.length; i++) {

}


example on a linked list:

for (LinkedListNode<int> X = List.First; X != null; X = X.Next) {

}


it's not always those breaks that you're concerned about, it's really nice when the loop itself can drive the flow. Compare reading that to something like this..

LinkedListNode<int> X = List.First;

while (X != null) {

     //do something

     X = X.Next;

}


I could agree that it's all a matter of style, but in my opinion the for loop is much cleaner.

What do you think?




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users