C# goto user input - c#

I am making an OS with Cosmos and want to use goto to go to the user input but I am getting the error
No such label 'input' within the scope of the goto statement
'input' is a variable in which the user has inputted.
I can understand why this is happening but how do I fix it?

You cannot user variables as scope identifier for goto statement.. you have to use label identifier within scope (namespace) indicating it by ":" ..
for example
using System;
class Program
{
static void Main()
{
Console.WriteLine(M());
}
static int M()
{
int dummy = 0;
for (int a = 0; a < 10; a++)
{
for (int y = 0; y < 10; y++) // Run until condition.
{
for (int x = 0; x < 10; x++) // Run until condition.
{
if (x == 5 &&
y == 5)
{
goto Outer;
}
}
dummy++;
}
Outer:
continue;
}
return dummy;
}
}
method M contains three nested loops. The first loop iterates through numbers [0, 9], as do the two inner loops. But in the third loop, a condition is checked that causes the loop to exit using the break keyword.
For
Break
The code increments the dummy variable after each completion of the inner loop. If the inner loop is exited early, this variable should be left alone. With the goto statement, it is not incremented.
Result:
The value 50 is printed to the console. The int is incremented 10 x 5 times.
However:
If the goto was a break, the result would be 10 x 10 times, or a total of 100.
Hope this Help.. :)

I am making an OS with Cosmos
For getting any remotely useful answers, I think you will have to give some information about the scope of the OS. Are you only fiddling around with COSMOS a bit, or do you have some special use-case you want to serve with a custom COSMOS OS?
and want to use goto to go to the user input
Especially in the latter case (specialized OS) you should clearly refrain from using GOTO, unless you have a very good reason to do so (and in my humble opinion there is no such thing as a really good reason to use GOTO). There are viable alternatives to GOTOs in modern programming languages and you should re-think your design, algorithm, whatsoever.
To answer your question. Here is an example that produces the very error message you are experiencing
private void FirstMethod()
{
goto MyLabel;
}
private void SecondMethod()
{
MyLabel:
return;
}
I have defined a label in Method. Anyway, from Main you cannot simply jump from main to another method, since the compiler would not know where to return to, after the method has finished, since no data would have been pushed to the call stack on GOTO (please see the Wikipedia page about the call stack for further information).
The following, anyway, would work, since the label and the GOTO live within the same scope
void MyMethod()
{
goto MyLabel;
// do something
MyLabel:
return;
}

Related

Equivalent of Ruby "redo" in C#

Is there an equivalent method of performing the job of redo in C#? i.e. going back to the top of the loop and re-execute without checking conditions or increasing the loop counter. Thanks.
for (int i = 0; i < 100; i++)
{
do
{
DoYourStuff();
} while (ShouldWeDoThatAgain());
}
Do...while is like a standard while loop, except instead of checking its conditional before each iteration, it checks after. That way, the code inside the loop will always execute at least once. Stick that inside a for or foreach loop, and that should get you the behavior your want. This is a bit simpler than Simon's answer, as it doesn't require an extra variable, doesn't use continue, and doesn't mess with the loop counter at all.
Why not simply:
Although goto is not really everyone's favourite, it's quite readable in this case...
for(...)
{
redo:
//...
if (...)
goto redo;
}
No. The closest you'll get is something like this:
bool redoCalled = false:
for (int i = 0; i < 10; i++) {
if (redoCalled) {
i--;
redoCalled = false;
}
// other stuff here
if (redoWanted) {
redoCalled = true;
continue;
}
}

Is goto ok for breaking out of nested loops?

JavaScript supports a goto like syntax for breaking out of nested loops. It's not a great idea in general, but it's considered acceptable practice. C# does not directly support the break labelName syntax...but it does support the infamous goto.
I believe the equivalent can be achieved in C#:
int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
for(int j = 0; j < 3; j++)
if (i > 5)
{
goto Break;//break out of all loops
}
}
Break:
By the same logic of JavaScript, is nested loop scenario an acceptable usage of goto? Otherwise, the only way I am aware to achieve this functionality is by setting a bool with appropriate scope.
My opinion: complex code flows with nested loops are hard to reason about; branching around, whether it is with goto or break, just makes it harder. Rather than writing the goto, I would first think really hard about whether there is a way to eliminate the nested loops.
A couple of useful techniques:
First technique: Refactor the inner loop to a method. Have the method return whether or not to break out of the outer loop. So:
for(outer blah blah blah)
{
for(inner blah blah blah)
{
if (whatever)
{
goto leaveloop;
}
}
}
leaveloop:
...
becomes
for(outer blah blah blah)
{
if (Inner(blah blah blah))
break;
}
...
bool Inner(blah blah blah)
{
for(inner blah blah blah)
{
if (whatever)
{
return true;
}
}
return false;
}
Second technique: if the loops do not have side effects, use LINQ.
// fulfill the first unfulfilled order over $100
foreach(var customer in customers)
{
foreach(var order in customer.Orders)
{
if (!order.Filled && order.Total >= 100.00m)
{
Fill(order);
goto leaveloop;
}
}
}
leaveloop:
instead, write:
var orders = from customer in customers
from order in customer.Orders;
where !order.Filled
where order.Total >= 100.00m
select order;
var orderToFill = orders.FirstOrDefault();
if (orderToFill != null) Fill(orderToFill);
No loops, so no breaking out required.
Alternatively, as configurator points out in a comment, you could write the code in this form:
var orderToFill = customers
.SelectMany(customer=>customer.Orders)
.Where(order=>!order.Filled)
.Where(order=>order.Total >= 100.00m)
.FirstOrDefault();
if (orderToFill != null) Fill(orderToFill);
The moral of the story: loops emphasize control flow at the expense of business logic. Rather than trying to pile more and more complex control flow on top of each other, try refactoring the code so that the business logic is clear.
I would personally try to avoid using goto here by simply putting the loop into a different method - while you can't easily break out of a particular level of loop, you can easily return from a method at any point.
In my experience this approach has usually led to simpler and more readable code with shorter methods (doing one particular job) in general.
Let's get one thing straight: there is nothing fundamentally wrong with using the goto statement, it isn't evil - it is just one more tool in the toolbox. It is how you use it that really matters, and it is easily misused.
Breaking out of a nested loop of some description can be a valid use of the statement, although you should first look to see if it can be redesigned. Can your loop exit expressions be rewritten? Are you using the appropriate type of loop? Can you filter the list of data you may be iterating over so that you don't need to exit early? Should you refactor some loop code into a separate function?
IMO it is acceptable in languages that do not support break n; where n specifies the number of loops it should break out.
At least it's much more readable than setting a variable that is then checked in the outer loop.
I believe the 'goto' is acceptable in this situation. C# does not support any nifty ways to break out of nested loops unfortunately.
It's a bit of a unacceptable practice in C#. If there's no way your design can avoid it, well, gotta use it. But do exhaust all other alternatives first. It will make for better readability and maintainability. For your example, I've crafted one such potential refactoring:
void Original()
{
int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
if (Process(i))
{
break;
}
}
}
bool Process(int i)
{
for(int j = 0; j < 3; j++)
if (i > 5)
{
return true;
}
return false;
}
I recommend using continue if you want to skip that one item, and break if you want to exit the loop. For deeper nested put it in a method and use return. I personally would rather use a status bool than a goto. Rather use goto as a last resort.
anonymous functions
You can almost always bust out the inner loop to an anonymous function or lambda. Here you can see where the function used to be an inner loop, where I would have had to use GoTo.
private void CopyFormPropertiesAndValues()
{
MergeOperationsContext context = new MergeOperationsContext() { GroupRoot = _groupRoot, FormMerged = MergedItem };
// set up filter functions caller
var CheckFilters = (string key, string value) =>
{
foreach (var FieldFilter in MergeOperationsFieldFilters)
{
if (!FieldFilter(key, value, context))
return false;
}
return true;
};
// Copy values from form to FormMerged
foreach (var key in _form.ValueList.Keys)
{
var MyValue = _form.ValueList(key);
if (CheckFilters(key, MyValue))
MergedItem.ValueList(key) = MyValue;
}
}
This often occurs when searching for multiple items in a dataset manually, as well. Sad to say the proper use of goto is better than Booleans/flags, from a clarity standpoint, but this is more clear than either and avoids the taunts of your co-workers.
For high-performance situations, a goto would be fitting, however, but only by 1%, let's be honest here...
int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
for(int j = 0; j < 3 && i <= 5; j++)
{
//Whatever you want to do
}
}
Unacceptable in C#.
Just wrap the loop in a function and use return.
EDIT: On SO, downvoting is used to on incorrect answers, and not on answers you disagree with. As the OP explicitly asked "is it acceptable?", answering "unacceptable" is not incorrect (although you might disagree).

CLR is optimising my forloop variables away

I'm trying to run a basic loop that will find a specific value in a dataview grid. I cannot figure out whats going on with the code, since the for loop exits before evaluating its basic condition.
private void SearchDataViewGrid(string FileName)
{
//finds the selected entry in the DVG based on the image
for (int i = 0; i == dataPartsList.Rows.Count ; i++)
{
if(FileName == dataPartsList.Rows[i].Cells[3].Value.ToString())
{
dataPartsList.Rows[i].Selected = true;
}
}
}
The program doesn't crash, but i get an error on my 'i' variables declaring that it has been optimised away. Tried a few easy fixes i found online but nothing seems to keep it.
I have verified that the string i am passing is the correct one, and my 'dummy' DVG returns a value of 14 for the number of rows contained. Even if i remove the 'if' statement inside of the for loop, i still get the same error.
The condition cond in the middle of for(init; cond; update) is not an until condition but a while condition.
So you need to change it to
for (int i = 0; i < dataPartsList.Rows.Count ; i++)
The problem is your conditional is i == dataPartsList.Rows.Count so the body will only execute when these two values are equal. This guarantees your loop will never execute. You need to change your conditional to be < instead of ==
for (int i = 0; i < dataPartsList.Rows.Count ; i++) {
...
}

will declaring variables inside sub-blocks improve performance?

In C#, would there be any difference in performance when comparing the following THREE alternatives?
ONE
void ONE(int x) {
if (x == 10)
{
int y = 20;
int z = 30;
// do other stuff
} else {
// do other stuff
}
}
TWO
void TWO(int x) {
int y;
int z;
if (x == 10)
{
y = 20;
z = 30;
// do other stuff
} else {
// do other stuff
}
}
THREE
void THREE(int x) {
int y = 20;
int z = 30;
if (x == 10)
{
// do other stuff
} else {
// do other stuff
}
}
All else being equal (and they usually aren't, which is why you normally have to actually test it), ONE() and TWO() should generate the same IL instructions since local variables end up scoped to the whole method. THREE() will be negligibly slower if x==10 since the other two won't bother to store the values in the local variables.
All three take up the same amount of memory—the memory for all variables is allocated even if nothing is stored in them. The JIT compiler may perform an optimization here, though, if it ever looks for unused variables.
There no performance difference, but you're going to find variable scope issues between each of those examples.
You're also showing three different intents between those examples, which isn't what you want:
y and z are limited to the scope of the if statement.
y and z are used outside of the if statement, but are set conditionally.
y and z have nothing to do with the if statement whatsoever.
Of course, you should always pick ONE, it is much more readable. That it is faster by a fraction of a nanosecond isn't an accident, readable code often is.
I don't think it'll make much difference. The only time you would need to worry is if creating the new object and initializing it is expensive. You could always try to profile each method a couple thousand times to see if there are any differences but I doubt you'll find any.
The only time I move a declaration further away from where it's used is if it'll be worked on in a loop. e.g.:
void RunMethod() {
FormRepresentation formRep = null;
for (int idx = 0; idx < 10; idx++) {
formRep = new FormRepresentation();
// do something
}
}
It doesn't actually make any difference since the object is still being created but, to me, it looks cleaner. The other thing you need to consider is the scope of the variable. Declared variables cannot be used outside the scope they were declared in.

Do .. While loop in C#?

How do I write a Do .. While loop in C#?
(Edit: I am a VB.NET programmer trying to make the move to C#, so I do have experience with .NET / VB syntax. Thanks!)
The general form is:
do
{
// Body
} while (condition);
Where condition is some expression of type bool.
Personally I rarely write do/while loops - for, foreach and straight while loops are much more common in my experience. The latter is:
while (condition)
{
// body
}
The difference between while and do...while is that in the first case the body will never be executed if the condition is false to start with - whereas in the latter case it's always executed once before the condition is ever evaluated.
Since you mentioned you were coming from VB.NET, I would strongly suggest checking out this link to show the comparisons. You can also use this wensite to convert VB to C# and vice versa - so you can play with your existing VB code and see what it looks like in C#, including loops and anything else under the son..
To answer the loop question, you simple want to do something like:
while(condition)
{
DoSomething();
}
You can also do - while like this:
do
{
Something();
}
while(condition);
Here's another code translator I've used with success, and another great C#->VB comparison website. Good Luck!
//remember, do loop will always execute at least once, a while loop may not execute at all
//because the condition is at the top
do
{
//statements to be repeated
} while (condition);
Quite surprising that no one has mentioned yet the classical example for the do..while construct. Do..while is the way to go when you want to run some code, check or verify something (normally depending on what happened during the execution of that code), and if you don't like the result, start over again. This is exactly what you need when you want some user input that fits some constraints:
bool CheckInput(string input) { ... }
...
string input;
...
do {
input=Console.ReadLine();
} while(!CheckInput(input));
That's quite a generic form: when the condition is simple enough, it's common to place it directly on the loop construct (inside the brackets after the "while" keyword), rather than having a method to compute it.
The key concepts in this usage are that you have to request the user input at least once (in the best case, the user will get it right at the first try); and that the condition doesn't really make much sense until the body has executed at least once. Each of these are good hints that do..while is the tool for the job, both of them together are almost a guarantee.
Here's a simple example that will print some numbers:
int i = 0;
do {
Console.WriteLine(++i);
} while (i < 10);
using System;
class MainClass
{
public static void Main()
{
int i = 0;
do
{
Console.WriteLine("Number is {0}", i);
i++;
} while (i < 100);
}
}
Another method would be
using System;
class MainClass
{
public static void Main()
{
int i = 0;
while(i <100)
{
Console.WriteLine("Number is {0}", i);
i++;
}
}
}
The answer by Jon Skeet is correct and great, though I would like to give an example for those unfamiliar with while and do-while in c#:
int i=0;
while(i<10)
{
Console.WriteLine("Number is {0}", i);
i++;
}
and:
int i=0;
do
{
Console.WriteLine("Number is {0}", i);
i++;
}while(i<10)
will both output:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
as we would expect. However it is important to understand that the do-while loop always executes the body the first time regardless of the check. This means that if we change i's starting value to 100 we will see very different outputs.
int i=100;
while(i<10)
{
Console.WriteLine("Number is {0}", i);
i++;
}
and:
int i=100;
do
{
Console.WriteLine("Number is {0}", i);
i++;
}while(i<10)
Now the while loop actually generates no output:
however the do-while loop generates this:
Number is 100
despite being well over 10. This is because of the unique behavior of a do-while loop to always run once unlike a regular while loop.
Apart from the Anthony Pegram's answer, you can use also the while loop, which checks the condition BEFORE getting into the loop
while (someCriteria)
{
if (someCondition)
{
someCriteria = false;
// or you can use break;
}
if (ignoreJustThisIteration)
{
continue;
}
}

Categories

Resources