Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How goto statement works in this example?

Tags:

c#

goto

I am studying this code sample:

class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = 10;

        int generate=0;

        string [,] myArrayTable = new string[x, y];

        Console.WriteLine("Enter a seek number: ");
        string cautat = Console.ReadLine();

        for (int i = 0; i < x; i++)
        {
            for(int j = 0;j < y; j++)
            {
                myArrayTable[i, j] = (generate++).ToString();
            }
        }

        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(cautat.Equals(myArrayTable[i,j]))
                {
                    goto Found; 
                }
            }
        }

        goto NotFound;

        Found: 
          Console.WriteLine("Numarul a fost gasit");

        NotFound:
         Console.WriteLine("Numarul nu a fost gasit !");

        Console.ReadKey();
    }
}

I do not understand why the "Not Found" statement was called and its corresponding message print on console if i enter a seek number like 10, in this case goto: Found statement is executing, so goto: NotFound statement will never be called, but still its corresponding message is printed on console, i do not understand how since in this case program never jumps to this "NotFound" label.

Please if you now give me a hand about this...

Thanks

like image 493
Mircea Avatar asked Aug 31 '10 16:08

Mircea


People also ask

How does a goto statement work?

The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.

How does a goto statement transfer control?

GoTo transfers control conditionally. The syntax is: On expression GoTo label, [ , label ]... The statement transfers control to a target label depending on the value of expression: It transfers control to the first label if expression is 1, to the second label if expression is 2, and so on.


1 Answers

Eww goto's, I would use and if/else statement, but if you need goto's:

Found: 
  Console.WriteLine("Numarul a fost gasit");
  goto End;
NotFound:
  Console.WriteLine("Numarul nu a fost gasit !");
End:
Console.ReadKey();
like image 56
SwDevMan81 Avatar answered Oct 06 '22 05:10

SwDevMan81