$ cat doloop.c #include <stdio.h> int x=0; int main(){
do {
x++;
printf("%d\n",x);
} while(x<100); }
$ cat goto.c #include <stdio.h> int x=0; int main(){ main:
x++;
printf("%d\n",x);
if(x<100){
goto main;
} }
$ cat recursive.c #include <stdio.h> int x=0; int main(){
x++;
printf("%d\n",x);
if(x<100){
main();
} }
$ cc --version cc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
再帰とループの違いが全くわからん (スコア:2)
/* どうちがうのか、自分には全くわからない。gotoは0引数の自分への再帰でしょう? */
/* 末尾最適化できないのはコンパイラかプログラマがタコなだけ。 */
#include <stdio.h>
int x=0;
int main(){
main:
x++;
printf("%d\n",x);
if(x<100){
goto main;
}else{
exit 0;
}
}
#include <stdio.h>
int x=0;
int main(){
x++;
printf("%d\n",x);
if(x<100){
main();
新人。プログラマレベルをポケモンで言うと、コラッタぐらい
Re:再帰とループの違いが全くわからん (スコア:0)
/* どうちがうのか、自分には全くわからない。gotoは0引数の自分への再帰でしょう? */
/* 末尾最適化できないのはコンパイラかプログラマがタコなだけ。 */
確かに。
$ cat doloop.c
#include <stdio.h>
int x=0;
int main(){
do {
x++;
printf("%d\n",x);
} while(x<100);
}
$ cat goto.c
#include <stdio.h>
int x=0;
int main(){
main:
x++;
printf("%d\n",x);
if(x<100){
goto main;
}
}
$ cat recursive.c
#include <stdio.h>
int x=0;
int main(){
x++;
printf("%d\n",x);
if(x<100){
main();
}
}
$ cc --version
cc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ cc -S -O3 doloop.c goto.c recursive.c
$ diff doloop.s recursive.s
1c1
< .file "doloop.c"
---
> .file "recursive.c"
$ diff doloop.s goto.s
1c1
< .file "doloop.c"
---
> .file "goto.c"
11a12
> .L2:
22c23
< .L2:
---
> .L3:
31c32
< jle .L2
---
> jle .L3
$ for f in *.s
> do
> echo '1
> s/"[^\.]*\./"a\./p
> wq
> ' | ed $f
> done
772
.file "doloop.c"
.file "a.c"
767
775
.file "goto.c"
.file "a.c"
772
775
.file "recursive.c"
.file "a.c"
767
$ cc -c *.s
$ for f in *.o
> do
> md5sum $f
> done
6109a31350e383fb5edde3565fcb3c7c doloop.o
6109a31350e383fb5edde3565fcb3c7c goto.o
6109a31350e383fb5edde3565fcb3c7c recursive.o
オブジェクトレベルでは、まったく同じであり、アセンブラレベルでの違いは、
goto.s の場合だけ、利用されていない L2 が追加され (た、結果として、名前が
ずれて、doloop.s/recursive.s の L2 と同じ役割をするラベルが L3 と変化し)
ただけの違いって事なんですね。