3 ms·
Any decent C/C++ compiler will give the same code. For example, this: int f1(int n) { int sum = 0; for (int i = 0; i < n; i++) {
by anon946 9y ago
Any decent C/C++ compiler will give the same code. For example, this:
int f1(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int x = i + i;
sum = x - i;
}
return sum;
}
int f2(int n) {
int sum = 0;
int x;
for (int i = 0; i < n; i++) {
x = i + i;
sum = x - i;
}
return sum;
}
when compiled with 'gcc -O -S' gives:
.file "loop.c"
.text
.globl f1
.type f1, @function
f1:
.LFB0:
.cfi_startproc
testl %edi, %edi
jle .L4
movl $0, %eax
.L3:
addl $1, %eax
cmpl %eax, %edi
jne .L3
subl $1, %eax
ret
.L4:
movl $0, %eax
ret
.cfi_endproc
.LFE0:
.size f1, .-f1
.globl f2
.type f2, @function
f2:
.LFB1:
.cfi_startproc
testl %edi, %edi
jle .L9
movl $0, %eax
.L8:
addl $1, %eax
cmpl %eax, %edi
jne .L8
subl $1, %eax
ret
.L9:
movl $0, %eax
ret
.cfi_endproc
.LFE1:
.size f2, .-f2
.ident "GCC: (GNU) 7.2.0"
.section .note.GNU-stack,"",@progbits
Even when compiled without optimization, the generated assembly was the same, though it was messier so I don't show it.