Search code examples
c#iterationgoto

C# label gives an iteration


I just started learning C# couple of days ago. When came learn goto statement, I found the example like this.

        ineligible:
            Console.WriteLine("Not eligible for voting");

            Console.WriteLine("Enter your age");
            int age = int.Parse(Console.ReadLine());


            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }

Then, I changed the code like this.

            int age = int.Parse(Console.ReadLine());

        ineligible:
            Console.WriteLine("Not eligible for voting");

            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }

and I got an infinite iteration Not eligible for voting. Image of the iteration

Why an iteration happened instead of printing Not eligible only once ?

Reference: javatpoint - C#(goto statement)


Solution

  • You are not supposed to use this anywhere in your life. After reading this change the code, try once, learn it and then forget it.

    Why your first case worked?

    Because you have Console.Readline() so it will wait for your response.

    ineligible:
            Console.WriteLine("Not eligible for voting");
    
            Console.WriteLine("Enter your age");
            int age = int.Parse(Console.ReadLine());
    
    
            if (age < 18)
            {
                goto ineligible;
            }
    

    Why second case leads to infinite loop?

    Because you have brought ineligible: just below to Console.ReadLine() statement.

    int age = int.Parse(Console.ReadLine());
    
            ineligible:
                Console.WriteLine("Not eligible for voting");
    

    So the loop will be forever and it wont expect your input or disturbance.

    Again learn it and forget it.