C while(1)真的是无限的吗?
我有这个计划:C while(1)真的是无限的吗?,c,loops,C,Loops,我有这个计划: int main(){ while(1) printf("Hi\n"); } 这真的会永远重复吗?如果我放置,而(1),没有printf,重复次数是否相同?如果不是永远,堆栈何时溢出?该计划: int main(){ loop:; printf("Hi\n"); goto loop; } 和第一个一样吗?如果没有,区别是什么?您的两个程序是等效的。例如: #include <stdio.h> void f1(void) {
int main(){
while(1) printf("Hi\n");
}
这真的会永远重复吗?如果我放置,而(1)
,没有printf
,重复次数是否相同?如果不是永远,堆栈何时溢出?该计划:
int main(){
loop:;
printf("Hi\n");
goto loop;
}
和第一个一样吗?如果没有,区别是什么?您的两个程序是等效的。例如:
#include <stdio.h>
void f1(void)
{
while(1)
printf("Hi\n");
}
void f2(void)
{
loop:
printf("Hi\n");
goto loop;
}
查看输出二进制文件:
example.o:
(__TEXT,__text) section
_f1:
0000000000000000 pushq %rbp
0000000000000001 movq %rsp, %rbp
0000000000000004 pushq %rbx
0000000000000005 pushq %rax
0000000000000006 leaq L_str1(%rip), %rbx ## literal pool for: "Hi"
000000000000000d nopl _f1(%rax)
0000000000000010 movq %rbx, %rdi
0000000000000013 callq _puts
0000000000000018 jmp 0x10
000000000000001a nopw _f1(%rax,%rax)
_f2:
0000000000000020 pushq %rbp
0000000000000021 movq %rsp, %rbp
0000000000000024 pushq %rbx
0000000000000025 pushq %rax
0000000000000026 leaq L_str1(%rip), %rbx ## literal pool for: "Hi"
000000000000002d nopl _f1(%rax)
0000000000000030 movq %rbx, %rdi
0000000000000033 callq _puts
0000000000000038 jmp 0x30
请注意,它们包含相同的指令。是,
而(1)
将永远循环,或者至少直到您终止进程或机器崩溃。它相当于第二个程序。它不会递归,因此不存在堆栈溢出的可能性。只要1保持等于1,它就会重复。如果没有printf
,我认为您有未定义的行为。为什么您认为堆栈会溢出?那没有道理@将是C++的KRekkSB。我认为在C语言中它是被定义的。这有点奇怪,对吧there@Jon:事实上,只要1与零保持不同,它就会重复,这使我们处于更安全的位置。
example.o:
(__TEXT,__text) section
_f1:
0000000000000000 pushq %rbp
0000000000000001 movq %rsp, %rbp
0000000000000004 pushq %rbx
0000000000000005 pushq %rax
0000000000000006 leaq L_str1(%rip), %rbx ## literal pool for: "Hi"
000000000000000d nopl _f1(%rax)
0000000000000010 movq %rbx, %rdi
0000000000000013 callq _puts
0000000000000018 jmp 0x10
000000000000001a nopw _f1(%rax,%rax)
_f2:
0000000000000020 pushq %rbp
0000000000000021 movq %rsp, %rbp
0000000000000024 pushq %rbx
0000000000000025 pushq %rax
0000000000000026 leaq L_str1(%rip), %rbx ## literal pool for: "Hi"
000000000000002d nopl _f1(%rax)
0000000000000030 movq %rbx, %rdi
0000000000000033 callq _puts
0000000000000038 jmp 0x30