while(1){}是否与while(1)相同;

我只是想确定这个C代码:

while(flag==true) { } foo(); 

做同样的事情:

 while(flag==true); foo(); 

; 单独是C中的空语句

在你的情况下, {}; 在语法上是需要的,但他们做同样的事情:没有

相关: 在C中使用null语句

除了其他答案:它是一样的。

但我更喜欢这个:

 while (condition) { } foo(); 

对此:

 while (condition); foo(); 

因为如果你在一段时间后忘记分号,你的代码将编译正常,但它不会做你期望的:

 while(condition) // ; forgotten here foo(); 

实际上相当于:

 while(condition) { foo(); } 

是的,循环的空体等同于while();

是。 A ; 遵循可以跟随块的控制结构(例如, whilefor等),就好像它后面跟着一个空块一样。

是的 ,因为在while循环语句后面加分号表示空体,当条件变为false时,它会转到循环后的紧接的下一个语句。

是的 ,他们是一样的。

您可以生成代码的程序集,并亲眼看看它们生成相同的程序集。 (使用gcc filename.c -S -masm=intel -o ouputfilename

 #include int foo(void); int main(){ int flag; scanf("%d" , &flag); while(flag==1); foo(); } int foo(void){ int x = 2; return x*x; } 

 .LC0: .ascii "%d\0" .text .globl main .def main; .scl 2; .type 32; .endef .seh_proc main main: push rbp .seh_pushreg rbp mov rbp, rsp .seh_setframe rbp, 0 sub rsp, 48 .seh_stackalloc 48 .seh_endprologue call __main lea rax, -4[rbp] mov rdx, rax lea rcx, .LC0[rip] call scanf nop .L2: mov eax, DWORD PTR -4[rbp] cmp eax, 1 je .L2 call foo mov eax, 0 add rsp, 48 pop rbp ret .seh_endproc .globl foo .def foo; .scl 2; .type 32; .endef .seh_proc foo foo: push rbp .seh_pushreg rbp mov rbp, rsp .seh_setframe rbp, 0 sub rsp, 16 .seh_stackalloc 16 .seh_endprologue mov DWORD PTR -4[rbp], 2 mov eax, DWORD PTR -4[rbp] imul eax, DWORD PTR -4[rbp] add rsp, 16 pop rbp ret .seh_endproc .ident "GCC: (x86_64-posix-seh-rev1, Built by MinGW-W64 project) 6.3.0" .def scanf; .scl 2; .type 32; .endef 

当我改变的while(flag == 1); to while(flag==1){}汇编代码生成的是:


 .LC0: .ascii "%d\0" .text .globl main .def main; .scl 2; .type 32; .endef .seh_proc main main: push rbp .seh_pushreg rbp mov rbp, rsp .seh_setframe rbp, 0 sub rsp, 48 .seh_stackalloc 48 .seh_endprologue call __main lea rax, -4[rbp] mov rdx, rax lea rcx, .LC0[rip] call scanf nop .L2: mov eax, DWORD PTR -4[rbp] cmp eax, 1 je .L2 call foo mov eax, 0 add rsp, 48 pop rbp ret .seh_endproc .globl foo .def foo; .scl 2; .type 32; .endef .seh_proc foo foo: push rbp .seh_pushreg rbp mov rbp, rsp .seh_setframe rbp, 0 sub rsp, 16 .seh_stackalloc 16 .seh_endprologue mov DWORD PTR -4[rbp], 2 mov eax, DWORD PTR -4[rbp] imul eax, DWORD PTR -4[rbp] add rsp, 16 pop rbp ret .seh_endproc .ident "GCC: (x86_64-posix-seh-rev1, Built by MinGW-W64 project) 6.3.0" .def scanf; .scl 2; .type 32; .endef 

您可以看到两种情况下相关部分都相同。

  //Below Portion is same in both cases. .L2: mov eax, DWORD PTR -4[rbp] cmp eax, 1 je .L2 call foo mov eax, 0 add rsp, 48 pop rbp ret .seh_endproc .globl foo .def foo; .scl 2; .type 32; .endef .seh_proc foo