If we want to break and come out from loop we can either use keyword break or goto. One thing I noticed goto statement enable the execution to come out from loop and we can start the execution at a point where we want. But break statement come out from loop and continue the execution. It can't be used to start the execution at a point where we want.
In other words goto statement is flexible and break statement is not.
Is there any other differences?
Loading
Posted Oct 21, 2013, 3:38 PM
VulpesPosted Oct 21, 2013, 3:36 PM
Loops for this purpose are : for, foreach, while, do and switch.
It doesn't work with the if statement here as it's not a loop and not embedded within a loop.
Posted Oct 21, 2013, 3:18 PM
You developed a program in a website. I have some question about this program. If I use break statement, program is not execuating. Please explain the reason. Problem is highlighted.
using System;
class Program
{
static void Main()
{
Console.Write("Enter number of seats : ");
int numSeats = int.Parse(Console.ReadLine());
Console.Write("Enter number of passengers : ");
int passengers = int.Parse(Console.ReadLine());
if (passengers > numSeats)
{
Console.WriteLine("The number of passengers cannot exceed the number of seats");
return;
}
// create a Random object
Random rand = new Random();
// create an array of seats
int[] seats = new int[numSeats]; // all elements 0 by default
// for each passenger assign a seat at random if it's not already occupied
for (int i = 1; i <= passengers; i++)
{
while (true)
{
int nextSeat = rand.Next(0, numSeats); // excludes end-point
if (seats[nextSeat] == 0) // it's empty
{
seats[nextSeat] = i;
break;
}
}
}
Console.WriteLine("The following seats are occupied by the passengers shown\n");
Console.WriteLine("Seat Passenger");
Console.WriteLine("---- ---------\n");
for (int i = 0; i < numSeats; i++)
{
if (seats[i] > 0) // it's occupied
{
Console.WriteLine("{0, 3} {1, 3}", i + 1, seats[i]);
}
}
Console.WriteLine();
if (numSeats == passengers)
{
Console.WriteLine("There are no empty seats");
break;
}
Console.WriteLine("The following seats are empty\n");
Console.WriteLine("Seat");
Console.WriteLine("----\n");
for (int i = 0; i < numSeats; i++)
{
if (seats[i] == 0) // it's empty
{
Console.WriteLine("{0, 3}", i + 1);
}
}
Console.ReadKey();
}
}
VulpesPosted Oct 21, 2013, 2:57 PM
for(int i = 0; i < 10; i++)
{
Console.WriteLine(i);
if (i == 5) goto next;
}
next:
// some more code
So your description of what it does is accurate.
As you say, 'goto' is more flexible but this flexibility can get you into trouble leading to 'spaghetti' code.
For this reason, 'goto' tends to be frowned upon by professional developers though it does have some sensible uses. Check out my article on the subject:
http://www.c-sharpcorner.com/UploadFile/b942f9/acceptable-uses-for-the-goto-statement-in-C-Sharp/