gpt4 book ai didi

c# - GOTO 与 DO WHILE 的区别

转载 作者:行者123 更新时间:2023-11-30 13:30:36 27 4
gpt4 key购买 nike

以下 2 个 C# 代码段在执行上有差异吗?

do
{
Console.WriteLine(x.ToString());
++x;
}
while (x < 7);

label:
{
Console.WriteLine(x.ToString());
++x;
}
if (x < 7) goto label;

我想弄清楚为什么 goto 这么糟糕。谢谢。

编辑:如果我添加方括号,则片段非常相似。

EDIT2:在 Visual Studio 中,我点击了 Go to Disassembly,我得到了以下代码:

            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

            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

区别在于无条件跳转。

最佳答案

不,我什至认为一个while在后面是这样实现的。

使用 goto 的坏处是它鼓励在您的代码中来回切换(也称为术语“意大利面条代码”:一团糟)。它使您的代码极难阅读、调试和分析,并且会引入错误,因为您无法真正理解正在发生的事情。

while 的好处是, 可以理解它,编译器也可以理解它,因此它可以给您很好的警告。

关于c# - GOTO 与 DO WHILE 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669854/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com