编译器可以根据需要重新排序/修改您的代码,只要修改后的代码与按顺序执行的原始代码等效即可。所以吊装是允许的,但不是必需的。这是一种优化,并且完全是编译器特定的。
C++ 中的变量声明可以在您希望的任何位置。在 C 中,它们过去必须位于上下文的顶部,但是当引入 c99 标准时,规则被放宽,现在它们可以位于任何您想要的位置,类似于 C++。尽管如此,许多 C 程序员仍然坚持将它们放在上下文中的顶部。
在您的示例中,编译器可以自由地将 if 语句移至顶部,但我认为不会。这些变量只是在堆栈上声明且未初始化的指针,声明它们的成本是最小的,而且在函数开头而不是在断言之后创建它们可能更有效。
例如,如果您的声明会涉及任何副作用
struct node *a = some_function();
那么编译器可以重新排序的内容将受到限制。
Edit:
我用这个短程序在实践中检查了 GCC 的循环提升:
#include <stdio.h>
int main(int argc, char **argv) {
int dummy = 2 * argc;
int i = 1;
while (i<=10 && dummy != 4)
printf("%d\n", i++);
return 0;
}
我用这个命令编译它:
gcc -std=c99 -pedantic test.c -S -o test.asm
这是输出:
.file "test.c"
.def ___main; .scl 2; .type 32; .endef
.section .rdata,"dr"
LC0:
.ascii "%d\12\0"
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB7:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $32, %esp
call ___main
movl 8(%ebp), %eax
addl %eax, %eax
movl %eax, 24(%esp)
movl $1, 28(%esp)
jmp L2
L4:
movl 28(%esp), %eax
leal 1(%eax), %edx
movl %edx, 28(%esp)
movl %eax, 4(%esp)
movl $LC0, (%esp)
call _printf
L2:
cmpl $10, 28(%esp)
jg L3
cmpl $4, 24(%esp)
jne L4
L3:
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
LFE7:
.ident "GCC: (GNU) 4.8.2"
.def _printf; .scl 2; .type 32; .endef
然后我用这个命令编译它:
gcc -std=c99 -pedantic test.c -O3 -S -o test.asm
这是输出:
.file "test.c"
.def ___main; .scl 2; .type 32; .endef
.section .rdata,"dr"
LC0:
.ascii "%d\12\0"
.section .text.startup,"x"
.p2align 4,,15
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB7:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
pushl %ebx
andl $-16, %esp
subl $16, %esp
.cfi_offset 3, -12
call ___main
movl 8(%ebp), %eax
leal (%eax,%eax), %edx
movl $1, %eax
cmpl $4, %edx
jne L8
jmp L6
.p2align 4,,7
L12:
movl %ebx, %eax
L8:
leal 1(%eax), %ebx
movl %eax, 4(%esp)
movl $LC0, (%esp)
call _printf
cmpl $11, %ebx
jne L12
L6:
xorl %eax, %eax
movl -4(%ebp), %ebx
leave
.cfi_restore 5
.cfi_restore 3
.cfi_def_cfa 4, 4
ret
.cfi_endproc
LFE7:
.ident "GCC: (GNU) 4.8.2"
.def _printf; .scl 2; .type 32; .endef
基本上,打开优化后,原始代码将转换为如下所示:
#include <stdio.h>
int main(int argc, char **argv) {
int dummy = 2 * argc;
int i = 1;
if (dummy != 4)
while (i<=10)
printf("%d\n", i++);
return 0;
}
所以,正如你所看到的,C 中确实存在提升。