There are differences in execution between the 2 following C# snippets?
do
{
Console.WriteLine(x.ToString());
++x;
}
while (x < 7);
and
label:
{
Console.WriteLine(x.ToString());
++x;
}
if (x < 7) goto label;
I am trying to figure out why is goto so bad. Thanks.
EDIT: If I add brackets the snippets are pretty similar.
EDIT2: In Visual Studio I've clicked Go to Disassembly and I get the following code:
do
{
00000037 nop
Console.WriteLine(x.ToString());
00000038 lea ecx,[ebp-40h]
0000003b call 63129C98
00000040 mov dword ptr [ebp-48h],eax
00000043 mov ecx,dword ptr [ebp-48h]
00000046 call 63148168
0000004b nop
++x;
0000004c inc dword ptr [ebp-40h]
}
0000004f nop
while (x < 7);
00000050 cmp dword ptr [ebp-40h],7
00000054 setl al
00000057 movzx eax,al
0000005a mov dword ptr [ebp-44h],eax
0000005d cmp dword ptr [ebp-44h],0
00000061 jne 00000037
and
label:
{
Console.WriteLine(x.ToString());
00000069 lea ecx,[ebp-40h]
0000006c call 63129C98
00000071 mov dword ptr [ebp-4Ch],eax
00000074 mov ecx,dword ptr [ebp-4Ch]
00000077 call 63148168
0000007c nop
++x;
0000007d inc dword ptr [ebp-40h]
}
00000080 nop
if (x < 7) goto label;
00000081 cmp dword ptr [ebp-40h],7
00000085 setge al
00000088 movzx eax,al
0000008b mov dword ptr [ebp-44h],eax
0000008e cmp dword ptr [ebp-44h],0
00000092 jne 00000097
00000094 nop
00000095 jmp 00000068
The difference is unconditional jump.
No, I even think a while
is implemented like that in the back.
The thing bad in using goto
is that it encourages going back and forth in your code (also known with the term 'spaghetti code': it is a mess). It makes your code extremely hard to read, debug and analyse and it introduces bugs since you can't really understand what is going on.
The nice thing with while
is, that you can understand it, and the compiler can understand it, so it can give you nice warnings.