473,395 Members | 1,595 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Using "break" to Break Out of Multiple Loops in One Call

Does C# support anything like PHP's break command that optionally
accepts a parameter specifying how many loops to break out of?
Feb 15 '08 #1
11 9678
No - 'break' and 'continue' always apply to the innermost loop.
You will need to set and test flags to do what you want (or - gasp - goto).
--
http://www.tangiblesoftwaresolutions.com
C++ to C#
C++ to VB
C++ to Java
Instant C#: VB to C#
Instant VB: C# to VB
Instant C++: VB or C# to C++/CLI
Java to VB & C# Converter: Java to VB or C#
"O.B." wrote:
Does C# support anything like PHP's break command that optionally
accepts a parameter specifying how many loops to break out of?
Feb 15 '08 #2
On 15 Feb, 18:31, "O.B." <funkj...@bellsouth.netwrote:
Does C# support anything like PHP's break command that optionally
accepts a parameter specifying how many loops to break out of?
Not that Im aware of, and there would be grunts in the cleraing of
code if I found one...

for(;;int i(for(i=0;i<100;for(;console.writeline("{0}\n",i;f or(;;i+
+for(;;break(2))))));
have to try that... someday... it sholdnt work, but giving an example
of why not.. it should stop at writing nothing but who knows...
//CY
Feb 15 '08 #3
O.B. wrote:
Does C# support anything like PHP's break command that optionally
accepts a parameter specifying how many loops to break out of?
No. And that's not very nice to begin with (requiring the programmer to
count carefully). Labeled breaks a la Java would be better, but it doesn't
have that either.

If you really think it makes the code easier to read, you can always use
goto. If the "multi-level break" is to handle a rare error condition, you
could throw an exception instead. If that's the case, though, you should
probably split things up in multiple functions. That would also allow you to
use "return" to break out of all loops in the current function.

--
J.
Feb 15 '08 #4
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in
news:op***************@petes-computer.local:
Either way, I don't think there's anything inherently bad about
labeled "break" statements or "goto" statements. Sometimes they are
just what you need. Just remember not to aim at your foot when using
them. :)
There's nothing bad in goto. I just love the longjmp() !!
Feb 16 '08 #5
On Fri, 15 Feb 2008 17:26:49 -0800, Donkey Hot <sp**@plc.is-a-geek.com>
wrote:
There's nothing bad in goto. I just love the longjmp() !!
Well, sure. But these days we have exceptions to provide for that.

In fact, I'd say if anything, the descendant of longjmp() is much more
broadly accepted than that of goto. :)
Feb 16 '08 #6

"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
Personally, I'm not of the mind that "goto" statements are inherently
bad. They certainly can be misused, and may well be misused much more
than other language constructs. But they also have their place (and I
don't just mean as a replacement for falling through in "case" statements
:) ).
Would you mind providing one such example?

Feb 16 '08 #7
On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
<sr******@no.spam.here-webworks-software.comwrote:
>
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
>Personally, I'm not of the mind that "goto" statements are inherently
bad. They certainly can be misused, and may well be misused much more
than other language constructs. But they also have their place (and I
don't just mean as a replacement for falling through in "case"
statements :) ).

Would you mind providing one such example?
Well, one common scenario is error-handling. In some cases, it makes
sense to have a single exit point in a method so that things can be
cleaned up in a single block of code rather than repeating that code, or
some subset, throughout the method. Using a "goto" statement allows you
to place that cleanup in a single place (I generally put it at the end of
the method), jumping to it on an error, and otherwise falling straight
through.

Nesting a bunch of "if()" statements can accomplish the same thing, but it
can create a difficult-to-read pattern of indentation. Using a "goto"
provides a lot of the same readability benefits that using exceptions for
failures can as well.

Are there other ways to do that? Sure, especially in C# (which has
"using" as well as exceptions). But those alternatives don't always
result in code that's as readable. And does the presence of those
alternatives mean that a "goto" statement is bad? No, not at all. Only
someone who had a blanket objection to using a "goto" statement for the
sake of the objection would say it was.

The fact is, even if you never write a "goto" statement, you use "goto"s
all the time. As long as you're keeping the code structured as you use a
"goto" statement, you haven't done anything the compiler wouldn't do
anyway. And if the use of the "goto" makes the code more readable, then
that's an advantage over shoe-horning your code into whatever alternative
the language would require to accomplish the same thing.

Pete
Feb 16 '08 #8
On Feb 16, 3:11 pm, "Scott Roberts" <srobe...@no.spam.here-webworks-
software.comwrote:
"Peter Duniho" <NpOeStPe...@nnowslpianmk.comwrote in message

news:op***************@petes-computer.local...
On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
<srobe...@no.spam.here-webworks-software.comwrote:
"Peter Duniho" <NpOeStPe...@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
Personally, I'm not of the mind that "goto" statements are inherently
bad. They certainly can be misused, and may well be misused much more
than other language constructs. But they also have their place (and I
don't just mean as a replacement for falling through in "case"
statements :) ).
Would you mind providing one such example?
I am not Peter Duniho but I can provide you an example from a real
world high-performance middle-ware product. I lifted this piece out
of the codebase of this product (http://www.zeroc.com)

Consider this snippet that listens on a socket:

public static void doListen(Socket socket, int backlog)
{
repeatListen:

try
{
socket.Listen(backlog);
}
catch(SocketException ex)
{
if(interrupted(ex))
{
goto repeatListen;
}

closeSocketNoThrow(socket);
throw new Ice.SocketException(ex);
}
}

public static bool interrupted(Win32Exception ex)
{
return ex.NativeErrorCode == WSAEINTR;
}

There are probably other ways to do this without using goto but you
will only end up obfuscating the intent of the code for some mythical
purity.

Feb 17 '08 #9

"Dilip" <rd*****@lycos.comwrote in message
news:00**********************************@p25g2000 hsf.googlegroups.com...
On Feb 16, 3:11 pm, "Scott Roberts" <srobe...@no.spam.here-webworks-
software.comwrote:
>"Peter Duniho" <NpOeStPe...@nnowslpianmk.comwrote in message

news:op***************@petes-computer.local...
On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
<srobe...@no.spam.here-webworks-software.comwrote:
>"Peter Duniho" <NpOeStPe...@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
Personally, I'm not of the mind that "goto" statements are inherently
bad. They certainly can be misused, and may well be misused much
more
than other language constructs. But they also have their place (and
I
don't just mean as a replacement for falling through in "case"
statements :) ).
>Would you mind providing one such example?

I am not Peter Duniho but I can provide you an example from a real
world high-performance middle-ware product. I lifted this piece out
of the codebase of this product (http://www.zeroc.com)

Consider this snippet that listens on a socket:

public static void doListen(Socket socket, int backlog)
{
repeatListen:

try
{
socket.Listen(backlog);
}
catch(SocketException ex)
{
if(interrupted(ex))
{
goto repeatListen;
}

closeSocketNoThrow(socket);
throw new Ice.SocketException(ex);
}
}

public static bool interrupted(Win32Exception ex)
{
return ex.NativeErrorCode == WSAEINTR;
}

There are probably other ways to do this without using goto but you
will only end up obfuscating the intent of the code for some mythical
purity.
Hmmm, here's my attempt, but you may be right. I'll admit that the original
is pretty good. Thanks for the example.

// The intent here should be pretty clear: keep calling
// "tryListen" until it returns "true". Although, it's not
// entirely clear *why* tryListen might return false.
public static void doListen(Socket socket, int backlog)
{
while (!tryListen(socket, backlog)) ;

// or

bool success = tryListen(socket, backlog);
while (!success)
success = tryListen(socket, backlog);
}

// The intent here may be a little obfuscated. It's not clear
// at all that you are going to retry if "interrupted".
public static bool tryListen(Socket socket, int backlog)
{
try
{
socket.Listen(backlog);
}
catch(SocketException ex)
{
if(interrupted(ex))
{
// Listen failed, try again.
return false;
}

closeSocketNoThrow(socket);
throw new Ice.SocketException(ex);
}

// Listen succeeded.
return true;
}

public static bool interrupted(Win32Exception ex)
{
return ex.NativeErrorCode == WSAEINTR;
}

Feb 17 '08 #10
Dilip wrote:
>
I am not Peter Duniho but I can provide you an example from a real
world high-performance middle-ware product. I lifted this piece out
of the codebase of this product (http://www.zeroc.com)

Consider this snippet that listens on a socket:

public static void doListen(Socket socket, int backlog)
{
repeatListen:

try
{
socket.Listen(backlog);
}
catch(SocketException ex)
{
if(interrupted(ex))
{
goto repeatListen;
}

closeSocketNoThrow(socket);
throw new Ice.SocketException(ex);
}
}

public static bool interrupted(Win32Exception ex)
{
return ex.NativeErrorCode == WSAEINTR;
}
Hmm, I didn't know you could jump out of a try block with a goto, then re-enter
the block, very interesting...

How about:

public static void doListen(Socket socket, int backlog)
{
bool retry = true;
while (retry)
{
try
{
socket.Listen(backlog);
retry = false;
}
catch(SocketException ex)
{
if (!interrupted(ex))
{
closeSocketNoThrow(socket);
throw new Ice.SocketException(ex);
}
}
}
}

Feb 17 '08 #11
Another situation is where a particular operation will invalidate the
data being processes. For instance
start:
Generate dataset

for( - data set - )
while (something something)
for( - dataset - )
if (something something)
{
something that invalidates dataset
goto start:
}

*** Sent via Developersdex http://www.developersdex.com ***
Feb 19 '08 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else:...
27
by: Ron Adam | last post by:
There seems to be a fair amount of discussion concerning flow control enhancements lately. with, do and dowhile, case, etc... So here's my flow control suggestion. ;-) It occurred to me (a...
9
by: shannonl | last post by:
Hi all, For some reason this bind is calling the donothing function, like it should, but is then allowing the text to be inserted into the Text widget. Here is the code: ...
35
by: David Cleaver | last post by:
Hello all, I was wondering if there were some sort of limitations on the "if" statement? I'm writing a program which needs to check a bunch of conditions all at the same time (basically). And...
12
by: junky_fellow | last post by:
Which is better using a switch statement or the if-then equivalent of switch ?
15
by: cedmunds | last post by:
Group: We have an application that is calling a stored proc. The stored proc takes anywhere from 15 to 90 minutes to run. In order to keep the GUI responsive, we are using a BackgroundWorker...
4
by: Kevin Blount | last post by:
I've been unsuccessful finding a site that tells me, so I'm asking here: can I have multiple 'clauses' per 'case' in a 'switch' statement? e.g. switch "myVar" { case "1", "a": break;
7
by: andrewfsears | last post by:
I have a question: I was wondering if it is possible to simulate the multiple constructors, like in Java (yes, I know that the languages are completely different)? Let's say that I have a class...
94
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.