Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

A student's question

Name: Anonymous 2011-05-30 12:20

My teacher keeps drilling into our collective heads that using the break command is harmful, and that if we wish to terminate a loop early it would be far better to create a boolean variable, set it to 0, and add a condition to the head of the loop, and set the boolean variable to 1 when a break is needed. Note that this way you actually have to check this every single loop (where it is not needed almost every time) as well as waste a command to reset the boolean in case it was set to true.

Is there a reason to this?

Name: Anonymous 2011-05-31 8:48

>>108
I doubt the compiler would be able to replace that with a single jump (feel free to prove me wrong on this).
Let's try!

[/prog/ 0]=> cat goto.c
#include <stdio.h>
main(){int i,j,k;
     for(i=0;i++<1000;)
      for(j=0;j++<1000;)
           for(k=0;k++<1000;)
            if(i==j==k==500)goto breakall;
            else printf("%d:%d:%d",i,j,k);
breakall: return 0;}
[/prog/ 0]=> cat faggot.c
#include <stdio.h>
main(){int i,j,k;
     for(i=0;i++<1000;)
      for(j=0;j++<1000;)
           for(k=0;k++<1000;)
            if(i==j==k==500)i=j=k=1000;
            else printf("%d:%d:%d",i,j,k);
     return 0;}
[/prog/ 0]=> gcc -O3 goto.c -S
[/prog/ 0]=> gcc -O3 faggot.c -S
[/prog/ 0]=> diff -u goto.s faggot.s
--- goto.s    2011-05-31 14:41:25.000000000 +0200
+++ faggot.s    2011-05-31 14:41:30.000000000 +0200
@@ -1,4 +1,4 @@
-    .file    "goto.c"
+    .file    "faggot.c"
     .section    .rodata.str1.1,"aMS",@progbits,1
 .LC0:
     .string    "%d:%d:%d"
@@ -46,7 +46,6 @@
     addl    $1, %edi
     cmpl    $1001, %edi
     jne    .L2
-.L7:
     leal    -12(%ebp), %esp
     xorl    %eax, %eax
     popl    %ebx


Same with -O2, -O1 e no optimization flag. I didn't expect gcc to be this smart, actually.

Clang with no optimization, instead, sets them to 1000, and optimizes to a jmp in -O1.


[/prog/ 1]=> gcc --version
gcc (GCC) 4.6.0 20110513 (prerelease)
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.

[/prog/ 0]=> clang --version
clang version 2.9 (tags/RELEASE_29/final)
Target: i386-pc-linux-gnu
Thread model: posix

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List